1

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.

1
  • Should I use res.set()? And what should be the value and key? Commented Aug 15, 2017 at 15:49

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

4 Comments

I check if there is a OPTIONS request, and if that case I send 200. But there is only a OPTION request sent, and no POST request. Nothing more happens after the OPTIONS request.
What does the browser report on the Console in the Developer Tools have it receives the OPTIONS request? (I'd guess it is telling you that you can't put a wildcard for Access-Control-Allow-Origin when it is a preflighted request)
"Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response." I was dumb and just looked at the Network tab, not the console at first - therefore my first comment.
I forgot to add "Authorization" to the "Access-Control-Allow-Headers", it's working now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.