开发者

Catching XMLHttpRequest cross-domain errors

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 bec开发者_如何转开发ause the request is never made to begin with.

Is there any workaround?


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:

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.


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


Set a handler for onerror and you'll be able to catch the cross-domain exceptions. I don't know why the onerror event is fired for exceptions and not the error event, but I just tested it and it worked.

req = $.get('http://www.example.com');
req.onerror = function() { alert('An exception occurred.') };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜