现象
-
当出现403跨域错误的时候
No 'Access-Control-Allow-Origin' header is present on the requested resource
,需要给Nginx服务器配置响应的header参数 -
网上大多数的解决方案是:
-
只需要在Nginx的配置文件中配置以下参数:
-
事实上这个参数在我的 Nginx 1.12 上并不能用。
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}
解决方法
- 在nginx1.12版本之上使用以下的方式来解决跨域方式
location /agentProxy/{
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
proxy_pass http://agentProxy;
proxy_set_header Host $host;
}
网友评论