有预检请求的CORS帖子

rla*_*yte 5 javascript ajax cors

我正在尝试使用CORS将文件上传到不同域上的服务,但由于原因被拒绝,它们会一直失败.据我所知,正在使用正确的标头来允许这个.

Javascript请求:

  var xhr = new XMLHttpRequest();
  xhr.open('POST', "https://files.example.com", true);                                                                                                                            
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function () {
    if (this.status == 200 && this.readyState == 4) {
      console.log('response: ' + this.responseText);
    }
  };

  xhr.send();
Run Code Online (Sandbox Code Playgroud)

来自预检OPTIONS请求的响应:

Access-Control-Allow-Headers:Origin, Authorization, Content-Type
Access-Control-Allow-Methods:POST, OPTIONS
Access-Control-Allow-Origin:*
Content-Length:0
Content-Type:application/json
Date:Mon, 19 Nov 2012 23:30:21 GMT
Run Code Online (Sandbox Code Playgroud)

POST请求的标头:

Cache-Control:no-cache
Content-Type:application/json
Origin:https://www.example.com
Pragma:no-cache
Referer:https://www.example.com
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/537.19 (KHTML, like     Gecko) Chrome/25.0.1325.0 Safari/537.19
Run Code Online (Sandbox Code Playgroud)

这导致错误:

XMLHttpRequest cannot load https://files.example.com. Origin https://www.example.com is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

mon*_*sur 0

尝试将 Cache-Control 和 Pragma 添加到预检中允许的标头列表中。完整的标题应该如下所示:

Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type
Run Code Online (Sandbox Code Playgroud)