美文网首页我爱编程
Nginx 跨域 add_header 403状态下无效

Nginx 跨域 add_header 403状态下无效

作者: 勤劳一沙鸥 | 来源:发表于2018-05-24 16:26 被阅读515次

    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关键字。

    add_header解释

    最终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"
    

    相关文章

      网友评论

        本文标题:Nginx 跨域 add_header 403状态下无效

        本文链接:https://www.haomeiwen.com/subject/rwusjftx.html