Javascript 捕获 XMLHttpRequest 跨域错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5018566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catching XMLHttpRequest cross-domain errors
提问by kpozin
Is there any way to catch an error caused by Access-Control-Allow-Origin
when making a request? I'm using jQuery, and the handler set in .ajaxError()
never gets called because the request is never made to begin with.
有什么办法可以捕获Access-Control-Allow-Origin
在发出请求时引起的错误?我正在使用 jQuery,并且.ajaxError()
永远不会调用中设置的处理程序,因为从不开始请求。
Is there any workaround?
有什么解决方法吗?
回答by monsur
For CORS requests, the XmlHttpRequest's onError handler should fire. If you have access to the raw XmlHttpRequest object, try setting an event handler like:
对于 CORS 请求,应触发 XmlHttpRequest 的 onError 处理程序。如果您有权访问原始 XmlHttpRequest 对象,请尝试设置一个事件处理程序,例如:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'YOUR URL HERE';
var xhr = createCORSRequest('GET', url);
xhr.onerror = function() { alert('error'); };
xhr.onload = function() { alert('success'); };
xhr.send();
Note a few things:
请注意以下几点:
On CORS requests, the browser's console.log will display an error message. However, that error message is not available to your JavaScript code (I think this is done for security reasons, I asked this question once before: Is it possible to trap CORS errors?).
The xhr.status and xhr.statusText aren't set in the onError handler, so you don't really have any useful information as to why the CORS request failed. You only know that it failed.
对于 CORS 请求,浏览器的 console.log 将显示错误消息。但是,该错误消息对您的 JavaScript 代码不可用(我认为这是出于安全原因,我之前曾问过这个问题:是否可以捕获 CORS 错误?)。
xhr.status 和 xhr.statusText 未在 onError 处理程序中设置,因此您实际上没有任何关于 CORS 请求失败的有用信息。你只知道它失败了。
回答by Vikram Pudi
It is possible to get error status like so:
可以像这样获得错误状态:
xhr.onerror = function(e) {
alert("Error Status: " + e.target.status);
};
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
来源:https: //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
回答by Felipe Brahm
Set a handler for onerrorand you'll be able to catch the cross-domain exceptions. I don't know why the onerrorevent is fired for exceptions and not the errorevent, but I just tested it and it worked.
为onerror设置处理程序,您将能够捕获跨域异常。我不知道为什么onerror事件是针对异常而不是错误事件触发的,但我只是对其进行了测试并且它起作用了。
req = $.get('http://www.example.com');
req.onerror = function() { alert('An exception occurred.') };