此问题与跨源资源共享(CORS,http://www.w3.org/TR/cors/)有关.
如果在发出CORS请求时出错,Chrome(以及AFAIK其他浏览器)也会向错误控制台记录错误.示例消息可能如下所示:
XMLHttpRequest无法加载
http://domain2.example.原产地http://domain1.example不被访问控制允许来源允许的.
我想知道是否有办法以编程方式获取此错误消息?我试过xhr.send()在try/catch中包装我的调用,我也尝试添加一个onerror()事件处理程序.两者都没有收到错误消息.
我会通过使用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!');
}
Run Code Online (Sandbox Code Playgroud)
这是console.log错误:
XMLHttpRequest无法加载 http://test.testhost.com/testpage.请求标头字段Access-Control-Allow-Origin不允许使用Access-Control-Allow-Origin.
以下是标题信息:
> Remote Address:**.**.***.**:80 Request
> URL:http://test.testdomain.com/testpage Request
> Request Method:OPTIONS
> Status Code:200 OK
Run Code Online (Sandbox Code Playgroud)
请求标题:
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 …Run Code Online (Sandbox Code Playgroud)