我的 Nginx 中有这个配置
server {
listen 8080;
add_header Access-Control-Allow-Origin *;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
}
现在我的网络应用程序可以为 GET
执行 GET
和 POST
它工作正常,但如果我执行 Ajax POST
我收到此错误
XMLHttpRequest cannot load 'URL' . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'Origin' is therefore not allowed access. The response had HTTP status code 404.
如果我执行“GET”请求,我可以在响应中看到这一点。
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
但如果我发表帖子,我就看不到任何内容。
最佳答案
我遇到了同样的问题,并通过将关键字 always
添加到我的 add_header
指令中来解决。正如documentation所述:
add_header
: Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. [...]If the
always
parameter is specified (1.7.5), the header field will be added regardless of the response code.
发生的情况是,如果没有 always
,我的 GET
请求将返回 200
,因此具有预期的 header ,而我的 >POST
收到 400,因此没有 header ,从而触发 CORS 错误。
关于ajax - Nginx CORS 不适用于 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35946006/