捕获XMLHttpRequest跨域错误 [英] Catching XMLHttpRequest cross-domain errors

查看:2911
本文介绍了捕获XMLHttpRequest跨域错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提出请求时,是否有任何方法捕获 Access-Control-Allow-Origin 导致的错误?我使用jQuery,并且在 .ajaxError()中设置的处理程序从未被调用,因为请求从未被设置为开始。

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.

是否有解决方法?

推荐答案

对于CORS请求,XmlHttpRequest的onError处理程序应该启动。如果你有访问原始的XmlHttpRequest对象,请尝试设置一个事件处理程序,如:

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();

请注意以下几点:


  • 在CORS请求中,浏览器的console.log将显示一条错误消息。但是,该错误消息不可用于您的JavaScript代码(我认为这是为了安全原因,我问这个问题一次之前:

  • 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?).

xhr.status和xhr。可能会陷入CORS错误? statusText没有在onError处理程序中设置,所以你真的没有任何有用的信息,为什么CORS请求失败。您只知道它失败了。

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.

这篇关于捕获XMLHttpRequest跨域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆