Anubhav Dhawan Anubhav Dhawan - 2 months ago 7
Node.js Question

Cannot set headers

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:

Backend



// 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();
});


Frontend



$.ajax({
method: 'GET',
url: ...,
headers: {
Authentication: ...
},
...
});

Answer

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();

};