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?
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? 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.
CORS is a node. js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
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')) } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With