DEV Community

Discussion on: Build a REST API with Node, Express & MongoDB!

Collapse
 
vicentenoriega profile image
Vicente Noriega

How can I solve a Corss origin?, I'm calling localhost:3000/subscribers/ endpoint through react application which is running on localhost:3001

Collapse
 
miguelti profile image
Miguel Alemán

Hi, Vicente ! You can solve cross origin setting a header in your server definition.

res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
Enter fullscreen mode Exit fullscreen mode

But if you want you can delegate that to a lib called "cors" that you can install: github.com/expressjs/cors#installa...

And that you can use simply by calling it as a Middleware.

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
Enter fullscreen mode Exit fullscreen mode

It is important to remember that allowing cors without specifying a known domain could be dangerous since anyone would be able to reach your api, be careful and if you have any questions don't hesitate to ask :)

saludos, paisano !

Collapse
 
armanahmedjony profile image
Arman Ahemd

thanks brother for showing this.

Collapse
 
vicentenoriega profile image
Vicente Noriega

Hey thanks man for some reason I was missing put my domain there, but now it's work fine.

Gracias por el support carnal =).

Some comments have been hidden by the post's author - find out more