我本来可以通过使用 jQuery $.ajax
函数来解决这个问题,但在这种情况下,jQuery 不是选项。相反,我将使用 CORS 请求。我觉得响应请求的网络服务器有问题,我很难找出问题所在。
这是我创建 CORS 请求的代码
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');
httpRequest.setRequestHeader( 'Content-Type', 'application/json' );
httpRequest.onerror = function(XMLHttpRequest, textStatus, errorThrown) {
console.log( 'The data failed to load :(' );
console.log(JSON.stringify(XMLHttpRequest));
};
httpRequest.onload = function() {
console.log('SUCCESS!');
}
这是 console.log 错误:
XMLHttpRequest cannot load http://test.testhost.com/testpage. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.
这里是标题信息:
> Remote Address:**.**.***.**:80 Request
> URL:http://test.testdomain.com/testpage Request
> Request Method:OPTIONS
> Status Code:200 OK
请求 header :
OPTIONS /content-network HTTP/1.1
Host: test.testhost.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Access-Control-Request-Method: POST
Origin: http://test.testdomain.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin, content-type
Accept: */*
Referer: http://test.testdomain.com/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
响应 header :
HTTP/1.1 200 OK
Date: Thu, 14 Aug 2014 20:17:25 GMT
Server: Apache
Last-Modified: Thu, 14 Aug 2014 20:17:25 +0000
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: "1408047445"
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Vary: Accept-Encoding
Content-Encoding: gzip
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Content-Length: 6117
Connection: close
Content-Type: text/html; charset=utf-8
最佳答案
您的服务器的响应允许请求包含三个特定的 non-simple headers :
Access-Control-Allow-Headers:origin, x-requested-with, content-type
但是您的请求有一个服务器响应不允许的 header :
Access-Control-Request-Headers:access-control-allow-origin, content-type
Access-Control-Allow-Headers
响应 header 必须明确允许在 CORS 请求中发送的所有非简单 header 。服务器的 CORS 响应不允许在您的请求中发送不必要的 Access-Control-Allow-Origin
header 。这正是“...Access-Control-Allow-Headers
不允许”错误消息试图告诉您的内容。
请求没有理由具有此 header :它不执行任何操作,因为 Access-Control-Allow-Origin
是一个响应 header ,而不是请求 header .
解决方案:删除为您的请求添加 Access-Control-Allow-Origin
header 的 setRequestHeader
调用。
关于javascript - 使用 XMLHttpRequest 继续收到 No 'Access-Control-Allow-Origin' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25316393/