Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - CORS middleware `origin` undefined

Tags:

I have an app using the cors npm package as middleware. I have it set up like this:

  if(process.env.NODE_ENV === 'production') {     var whitelist = ['http://mywebsite.com', 'https://mywebsite.com']     var corsOptions = {       origin: (origin, callback) => {           var originIsWhitelisted = whitelist.indexOf(origin) !== -1;           console.log('ORIGIN: ', origin);  // => undefined           callback(originIsWhitelisted ? null : 'Bad Request', originIsWhitelisted)       },       credentials:true     }     app.use(cors(corsOptions));   } 

The origin parameter in my corsOptions is undefined. Why is this and how can I fix it?

like image 306
georgej Avatar asked Mar 03 '17 23:03

georgej


People also ask

How do I resolve a CORS issue in node JS?

To solve this error, we need to add the CORS header to the server and give https://www.section.io access to the server response. Include the following in your index. js file. const cors = require('cors'); app.

What is CORS error in node JS?

What is CORS? CORS stands for Cross-Origin Resource Sharing . It allows us to relax the security applied to an API. This is done by bypassing the Access-Control-Allow-Origin headers, which specify which origins can access the API.

What is middleware CORS?

CORS is a node. js package for providing a Connect/Express middleware that can be used to enable CORS with various options.


1 Answers

If you do not want to block REST tools or server-to-server requests, add a !origin check in the origin function like so:

var corsOptions = {   origin: function (origin, callback) {     if (!origin || whitelist.indexOf(origin) !== -1) {       callback(null, true)     } else {       callback(new Error('Not allowed by CORS'))     }   } } 
like image 138
Joan Galmés Riera Avatar answered Sep 19 '22 13:09

Joan Galmés Riera