WEB前后端分离的应用,前端跨域请求API服务器。这是前要。
当然,一开始直接上,js报报一堆 No 'Access-Control-Allow-Origin' header
的错误,那很明显了,nginx允许跨域的关键, 使用add_header
函数添加头即可。整理代码如下,添加在 location
节点
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' '1000';
add_header 'Access-Control-Allow-Methods' "POST, GET, OPTIONS, DELETE, PUT";
add_header 'Access-Control-Allow-Headers' "x-requested-with, Content-Type, origin, authorization, accept, client-security-token";
前端妹子测试,一切安好。
当然啦,问题肯定要来了,不然不在这里废话了。
一个表单验证,服务器返回422,并提示相应的错误信息。前端是死活无法显示。js报错如下:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://10.10.20.154:3000' is therefore not allowed access.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
也很好理解,没有跨域权限嘛。但是不对嘛,nginx 明明已经配置了。
仔细检查 POST 的记录,发现 Response Headers 没有 Access-Control那一堆。当然了,解决方法是有的,官方也给出了解释。只有在 状态码是 200,201,204,302.....的情况下,才有效。除非你使用always
关键字。
最终nginx配置成下边的样子,解决问题。
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Max-Age' '1000' always;
add_header 'Access-Control-Allow-Methods' "POST, GET, OPTIONS, DELETE, PUT" always;
add_header 'Access-Control-Allow-Headers' "x-requested-with, Content-Type, origin, authorization, accept, client-security-token" always;
Apache很好,在应用根目录下的 .htaccess 文件,贴入下内容即可:
Header always set Access-Control-Allow-Origin *
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, origin, authorization, accept, client-security-token"