【发布时间】: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