您的当前位置:首页正文

开发中的一些小事

来源:图艺博知识网
  • <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: *'; 
Top