美文网首页
开发中的一些小事

开发中的一些小事

作者: 坚果牛奶 | 来源:发表于2016-10-28 17:41 被阅读148次
    • <strong>跨域</strong>
      问题描述:
      php程序部署到nginx服务器,前端调用API报出跨域问题(200时没问题,422时出现此问题):
      [“No 'Access-Control-Allow-Origin' header is present on the requested resource”]
      检查nginx配置文件,包括允许跨域的配置如下:
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers X-Requested-With;
     add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    

    解决方案:
    出现此问题是因为add_header是针对200, 201, 204, 206, 301, 302, 303, 304, 307这些HTTP响应的,如果想要在响应等于4XX的时候也起作用需要添加always,所以配置应为:

    add_header Access-Control-Allow-Origin * always;
    add_header Access-Control-Allow-Headers X-Requested-With always;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS always;
    

    另一种解决方案是使用more_set_headers替换add_header,以便允许更多的响应跨域或是根据需要更灵活的配置响应值为对应值时可用。

    more_set_headers 'Access-Control-Allow-Origin: *'; 
    more_set_headers -s '404' 'Access-Control-Allow-Origin: *'; 
    

    more_set_headers需要nginx的扩展支持

    相关文章

      网友评论

          本文标题:开发中的一些小事

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