CORS and non 200 statusCode

泪湿孤枕 提交于 2019-12-01 15:20:39

问题


I have CORS working well with Nginx. The APIs are design to send non 200 status code - example 401, 404 etc - for bad input. The problem is that Chrome cancels / abort the request if it receives a non 200 status code. Due to this reason, I am not able to show the exact error on the Web client.

What is the way around for CORS non 200 status code errors?


回答1:


By default Nginx only adds headers for requests it considers successful. You can make it add the header without regard for the response code, by adding the always parameter to your add_header directive, e.g.

add_header 'Access-Control-Allow-Origin' '*' always;

Adding the 'always' parameter to the 'Access-Control-Allow-Origin' header is not enough. The 'always' parameter needs to be added to the headers that need to be always added. In some cases you will need to add the 'always' parameter to the 'Access-Control-Allow-Credentials' header.

add_header 'Access-Control-Allow-Credentials' 'true' always;



回答2:


You need to use the more_set_headers module.

with -s you can scpecify more status code

more_set_headers -s '404,400,403' 'Access-Control-Allow-Origin: http://domain.com';

However if you don't have installed this module in nginx you need to recompile it. to compile it :

wget http://nginx.org/download/nginx-1.7.8.tar.gz
git clone https://github.com/openresty/headers-more-nginx-module.git
tar -xzvf nginx-1.7.8.tar.gz
cd nginx-1.7.8
./configure --prefix=/opt/nginx --add-module=/path/to/headers-more-nginx-module
make
make install


来源:https://stackoverflow.com/questions/24162076/cors-and-non-200-statuscode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!