Getting express server to accept CORS request
I personally prefer the cors module. The code is really simple:
var whitelist = [ 'http://0.0.0.0:3000',];var corsOptions = { origin: function(origin, callback){ var originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); }, credentials: true};app.use(cors(corsOptions));
You also need to allow OPTIONS
method in the header.
I have this middleware for cors:
module.exports = function (req, res, next) { // CORS headers res.header("Access-Control-Allow-Origin", "YOUR_URL"); // restrict it to the required domain res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"); // Set custom headers for CORS res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header"); if (req.method === "OPTIONS") { return res.status(200).end(); } return next();};
PS. The error you get is due to the fact of how cross-origin request works. To make a long story short, the browser might first send a pre-flight
request with method OPTIONS
to get allowed origins, headers and methods. So for this request you should return nothing but the Access-Control-*
headers. If the pre-flight
went fine, the browser will continue with the original request.
You can find more information here.