gelv gelv -3 years ago 128
Node.js Question

Cors and headers

I'm having some trouble with cors and headers. I have the below middleware:

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type,X-Access-Token,Authorization');
next();


After that I have another middleware to check token:

const token = req.body.token || req.query.token || req.headers['x-access-token'];

if (token) {
jwt.verify(token, config.jwtKey, (err, decoded) => {
if(err) {
return res.json({success: false, errmsg: 'Wrong key'});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403)
.send({
success: false,
message: "No token provided"
});
}


But when I log req.headers:

{ host: 'localhost:4556',
connection: 'keep-alive',
'access-control-request-method': 'POST',
origin: 'http://localhost:4200',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'access-control-request-headers': 'authorization,content-type,x-access-token',
accept: '*/*',
dnt: '1',
referer: 'http://localhost:4200/posts',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'sv,en-US;q=0.8,en;q=0.6' }


There is no "X-access-token" in my headers, except in "access-control-request-headers". And it's only the name. Something must be wrong, but all i found when i googled was to use
Access-Control-Allow-Headers
.

Answer Source

You are looking at a preflight OPTIONS request. The can be triggered by a number of conditions, one of which is "Sets a non-standard header" (like X-access-token).

The browser won't make the POST request (with the X-access-token header) until the server responds to the OPTIONS request giving it permission.

You'll need to exclude OPTIONS requests from your token checking middleware so that you don't send 403 back in response to the preflight (which will never include the token).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download