Saturday 12 May 2018

express - Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response



I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradigm.




Before I simply added middleware in my express server to catch these things, but it looks like there is some kind of pre-hook that is erring out my requests.




Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response




I assumed that I could do this:



app.use(function(req, res, next) {

res.header("Access-Control-Allow-Headers","*")
})


or the equivalent but this doesn't seem to fix it. I also of course tried



app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers","Access-Control-Allow-Headers")
})



Still no luck.


Answer



When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS verb and includes several headers, one of which being Access-Control-Request-Headers listing the headers the client wants to include in the request.



You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).



https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...