1.问题描述:
前端域名A 在POST请求后端域名为B 的一个接口时候请求成功时不存在跨域问题,请求失败时浏览器提示跨域。
解决:
当请求成功时,HTTP CODE 为200。而请求失败时HTTP CODE 为400, 此时add_header ‘Access-Control-Allow-Origin’ ‘*’ 配置无效!设置无论HTTP CODE 为何值时都生效需要加 always 。nginx版本>1.7.5时候无须加always。
add_header ‘Access-Control-Allow-Origin’ ‘*’ always;
nginx文档地址:
http://nginx.org/en/docs/http/ngx_http_headers_module.html
文档原文:
Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in locationIf the always parameter is specified (1.7.5), the header field will be added regardless of the response code.
2.附配置:后端为PHP时需要将 add_header ‘Access-Control-Allow-Origin’ ‘’ always; 增加在 location ~.php{ } 的模块内。以下配置中add_header ‘Access-Control-Allow-Origin’ '’ always; 写在location ~.php{ } 上面一行无效的原因(已测试,正确),文档有写:
There could be several add_header directives. These directives are inherited from the previous level if and only if there are no add_header >directives defined on the current level.
当前层级无 add_header 指令时,则继承上一层级的add_header。相反的若当前层级有了add_header,就应该无法继承上一层的add_header。
server {
listen 80;
server_name localhost 127.0.0.1 demo.com;
root /www;
location ~ \.php {
client_body_timeout 6s;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Access-Control-Expose-Headers, Token, Authorization';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' '*' always;
fastcgi_pass unix:/run/php7.0-fpm.sock;
include snippets/fastcgi-php.conf;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
————————————————
原文链接:https://blog.csdn.net/xiojing825/java/article/details/83383524
网友评论