1
var enableCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

// intercept OPTIONS method
if ('OPTIONS' == req.method) {
  res.send(200);
}
else {
  next();
}
};
app.use(enableCORS);

I found out to use the following snippet in the server side, but still when i try to POST I am getting the error No 'Access-Control-Allow-Origin' header is present on the requested resource.

Dark Lord
  • 415
  • 5
  • 16

1 Answers1

5

I use only the following line:

res.header("Access-Control-Allow-Origin", "*");

And it works. Any chance you print anything else before sending the headers? headers must be sent before anything else. The middleware code should be prior to anything else.

Are you sure the code is getting executed? do some 'console.log' prints to make sure the enableCORS is being called.

Lastly, use chrome developer tools (or any equivalent tool) to view the headers returned from the server. For chrome, go to network => the problematic request => headers => Response headers, and make sure the CORS headers are there.

Update Try using the following (taken from here):

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); # OPTIONS removed
res.header('Access-Control-Allow-Headers', 'Content-Type');
Community
  • 1
  • 1
Kuf
  • 17,318
  • 6
  • 67
  • 91
  • "Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response." this is what i am getting at chrome console – Dark Lord Feb 10 '16 at 15:06
  • the headers are probably missing. try 'console.log' something before creating the headers and see it it gets executed at all. I've updated the answer with what to check on chrome – Kuf Feb 10 '16 at 15:20
  • console.log is printing but still the post request is not working and I am getting the same error. These are the response headers: Access-Control-Allow-Origin:* Allow:POST,GET,HEAD Connection:keep-alive Content-Length:13 Content-Type:text/html; charset=utf-8 Date:Wed, 10 Feb 2016 15:52:56 GMT ETag:W/"d-hXhJBegAzPe2v3FerP2DCw" X-Powered-By:Express – Dark Lord Feb 10 '16 at 15:55