【问题标题】:IE 11 XHR FailuresIE 11 XHR 失败
【发布时间】:2016-07-21 12:45:03
【问题描述】:

我的公司开发了一款可嵌入的 JavaScript 视频播放器。引导过程的一部分涉及使用XMLHttpRequest 从我们的服务器获取资源。这是一个跨域请求,因为我们的视频播放器通过脚本标签嵌入到其他人的网站上。我们正确配置了 CORS 标头,并且它可以在 Chrome、Firefox、Safari、iOS、Android 等中运行。当我在 IE 11 和 10 中测试时,它也适用于我。

但是,根据我们的分析数据,我们看到 xhr 对象在 IE 11 中大约 10% 的时间引发了 error 事件。我自己无法重现该问题。

谁能想到为什么会发生这种情况?我的最佳理论是某种企业 IE 安全设​​置阻止了我们的跨域请求。但这只是疯狂的猜测。

有没有其他人经历过这样的事情并找到了原因?

这是我为发出请求而编写的代码。我不相信我做错了什么。

function makeRequest(config) {
  var xhr = new window.XMLHttpRequest();
  var deferred = q.defer();
  var url;

  function setHeaders(headers) {
    var header;

    for (header in headers) {
      xhr.setRequestHeader(header, headers[header]);
    }
  }

  // toQueryParams() converts an object to URL query params
  url = config.url + toQueryParams(config.params);

  /*
  * This function gets called when the XHR is "loaded". It then fulfills or rejects
  * the promise based on the HTTP status code of the response.
  */
  function handleResponse() {
    var response = {
      status: xhr.status,
      data: (function() {
        try {
          return JSON.parse(xhr.responseText);
        } catch(e) {
          return xhr.responseText;
        }
      }()),
      headers: function() {
        return xhr.getAllResponseHeaders();
      }
    };
    var status = response.status,
    var success = !(status >= 400 && status < 600);

    deferred[success ? 'resolve' : 'reject'](response);
  }

  /*
  * This function gets called when the XHR emits an "error".
  *
  * There is code elsewhere that sends these errors to our Google Analytics
  * account. This is how we know about the IE 11 XHR errors even though I
  * can't reproduce them.
  */
  function handleError() {
    deferred.reject({
      status: null,
      data: new Error('The XHR request to [' + url + '] has failed...'),
      headers: function() {
        return null;
      }
    });
  }

  xhr.onload = handleResponse;
  xhr.onerror = handleError;

  xhr.open(config.method, url, true);

  xhr.responseType = config.responseType || '';
  setHeaders(config.headers);
  xhr.timeout = config.timeout || 0;

  xhr.send(config.data);

  return deferred.promise;
}

感谢您提供的任何帮助!

【问题讨论】:

    标签: javascript ajax internet-explorer xmlhttprequest


    【解决方案1】:

    不确定这是否仍然相关,但您的问题听起来很可疑 - this

    我也面临同样的问题。在我的例子中,当 IE 中止请求并且请求没有到达服务器时,就会发生这种情况。在这种情况下,xhr.status 为 0,response 为空,所以解析 JSON 会抛出异常。

    我无法找到一个万无一失的解决方案,但我的解决方法是如果响应与 IE 中止方案匹配,则在错误块中使用相同的参数/有效负载重试几次调用。

    干杯!

    【讨论】:

      猜你喜欢
      • 2015-12-27
      • 2019-03-29
      • 2015-04-19
      • 2013-08-31
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      相关资源
      最近更新 更多