Background
(If you are familiar with CORS, you might skip to the Question at the end)
CORS [1] is a solution to a
Now after much fiddling, I've managed to make it work. blush
There seems to be an awful lot of voodoo which makes up the exact scenario that ensures CORS will work in each browser, however having traced back numerous issues like:
Having stumbled upon what seemed to be a complete no-go, I ended up writing a CORS 4xx->200 wrapper as a jquery plugin,in an attempt to solve the issue. Debugging that plugin led me to my eventual fix.
I spend a couple of hours today hunting for the answer to this, while developing a web app on Chrome. Some others have written fairly detailed analyses of this situation.
There were two potential issues:
It could be that Chrome was doing a preflight and was getting a non-200 or a non-CORS response in response
For some reason my non-200 (error) status codes were not getting the headers attached. As I found out in this post, this second reason was the issue. Essentially, NGINX only adds headers on successful responses by default. To get my error responses through CORS, it sufficed to change
add_header 'Access-Control-Allow-Origin' '*';
to
add_header 'Access-Control-Allow-Origin' '*' always;
As the article notes, you may also have to add always
to 'Access-Control-Allow-Credentials'
and 'Access-Control-Allow-Headers'
. After doing this, all error codes also went through without CORS issues.
It may be that the program you are using for API serving does the same. Hope this helps and saves someone some time!
Just ran into this issue. Setting the HTTP headers for the 401 response did the trick for me. The library I was using wasn't doing this properly without some customization. e.g.:
self.headers["Access-Control-Max-Age"] = '1728000'
self.headers["Access-Control-Allow-Origin"] = "http://localhost:3001"
self.headers["Access-Control-Allow-Methods"] = "ANY"
self.headers["Access-Control-Allow-Credentials"] = 'true'