CORS issue with Node

So I am setting up an app to allow cross domain request. Been using a variety of methods from this post How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

However I get an error I can’t seem to sort out. Here’s what I am using (not that I tried about 3 of the methods outlined – they all give the same error).

 app.use(function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  next();
})
.options('*', function(req, res, next){
    res.end();
});

This gives me an error still:

XMLHttpRequest cannot load http://localhost:3000/blah. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

If I comment out the top code I get the expected not allowed error which seems to indicate that the request is properly being handled by that code. I have also retyped the content-type request to ensure that I had not pasted odd characters. Any clues?

Answer

You have two Access-Control-Allow-Headers headers. The last one’s going to win.

You probably want one Access-Control-Allow-Headers header with a value that’s a comma-separated list.

Leave a Reply

Your email address will not be published. Required fields are marked *