ajax - Nginx CORS 不适用于 POST

标签 ajax nginx cors

我的 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 执行 GETPOST 它工作正常,但如果我执行 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/

相关文章:

javascript - 如何调用媒体 RSS 提要

javascript - 未设置 CORS header - 我可以请求图像 url,然后将其返回给自己吗?

asp.net - 单个更新面板内 PostBackTrigger 的 ControlId 属性的多个控件

javascript - 如何从异步调用返回响应?

php - 当我尝试将 MySql 与 php 的 mysqli 连接时出现错误 500

django - 如何在Windows机器上使用Nginx运行django?

laravel cors "Class cors does not exist"错误

php - 使用 jQuery Ajax 解析 PHP 对象数组

ajax - AJAX 上的 301 重定向——重定向?

node.js - 使用 Apollo Express、Nginx 和 docker-compose 保护 Websocket