我正在尝试从客户端 javascript (fetch) 发送一个 post 请求到我的使用 Nginx 作为 Web 服务器的服务器。客户端 JavaScript 在不同的域上运行。
我在配置 Nginx 以使用正确的标头进行回复时遇到问题,当我尝试下面的配置时,我在预检请求中收到 405 不允许:
location /cookie/ {
root /myPlace;
add_header Allow 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
index index.php;
}
当我尝试下面的配置时,预检成功,它包含 CORS 所需的所有标头,但主要请求错误为 MissingAllowOriginHeader 控制台错误是熟悉的 没有“Access-Control-Allow-Origin”标头出现在所请求的资源上。
这是导致上述行为的配置:
location /cookie/ {
root /myPlace;
add_header Allow 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-headers' 'Content-Type' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
return 204;
}
index index.php;
}
奇怪的是,在这种情况下,主请求不会返回任何 CORS 标头,尽管预检具有所有必要的标头并且不会出错。
知道如何克服这些 CORS 错误吗
如果有帮助,这是我在客户端使用的 JavaScript 代码:
let theData = {
id: "123",
};
fetch("https://myServer.com/cookie/", {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(theData),
});
谢谢你
我没有足够的声誉来添加评论,但你找到解决方案了吗?