XHR发布请求因CORS而失败

XHR post requests fail with CORS

本文关键字:CORS 失败 请求 布请求 XHR      更新时间:2023-09-26

我想从另一个域test.example.com访问example.com。我已经将服务器example.com设置为使用CORS标头响应标头,如下所示(在nginx.conf中):

     add_header Access-Control-Allow-Origin $http_origin;
     add_header Access-Control-Allow-Credentials true;
     add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
     add_header Access-Control-Allow-Headers "*";

如果我发送一个GET请求,它可以成功,但如果我发送POST请求,它将失败,并出现以下错误:

XMLHttpRequest cannot load http://example.com/path. Origin http://test.example.com is not allowed by Access-Control-Allow-Origin.

我如何使用cors进行后期请求?

这取决于浏览器。有些浏览器不喜欢Access Control中的通配符。尝试将post请求的所有标头放入Access Control Allow headers(例如,从Access Control request headers)。

还请注意,对于基本的GET请求,您通常不需要任何特定的服务器扩展——这可能是GET工作的原因(请参阅https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)。

如果这不起作用:你能给我们更多关于你使用的浏览器以及它发出的请求的细节吗。