Reputation: 1487
This probably may be a duplicate question, but I'm not able to do this correctly.
I have enabled CORS in my backend (reading this). But, still, when I try to hit an API on my API server through my UI server, I get this:
Request header field Authentication is not allowed by Access-Control-Allow-Headers in preflight response.
Here are some relevant parts of my code:
// enable CORS
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
$.ajax({
method: 'GET',
url: ...,
headers: {
Authentication: ...
},
...
});
Upvotes: 0
Views: 162
Reputation: 12334
You need to allow that header explicitly
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authentication");
And you'd better use some existing CORS module, as I'm not sure your implementation is 100% correct.
I use this CORS middleware:
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,PATCH,POST,DELETE,OPTIONS");
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", YOUR_HEADER_STRING);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
};
Upvotes: 2
Reputation: 5069
I would like to recommend you to use express cors module like
var cors = require('cors');
// enable CORS
app.use(cors());
and do not forgot to install
npm install cors --save
Upvotes: 1