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

查看:65
本文介绍了捕获 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 代码无法使用该错误消息(我认为这是出于安全原因,我之前曾问过这个问题:是否可以捕获 CORS 错误?).

xhr.status 和 xhr.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天全站免登陆