我正在尝试向同一域上的资源发出 ajax 请求。在某些情况下,请求会被重定向 (303) 到外部资源。外部资源支持CORS。
在 Chrome、Firefox 或 Safari 等浏览器中,请求会成功。
在 IE11 中,请求失败并出现错误:
SCRIPT 7002: XMLHttpRequest: Network Error 0x4c7, The operation was canceled by the user
ajax 请求是使用 jQuery 发出的:
$.ajax({
url: "/data",
type: "POST",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({name: 'John Doe'})
}).done(function () {
console.log('succeeded');
}).fail(function () {
console.log('failed');
});
我构建了一些example这说明了问题所在。您可以看到代码 here .
不带重定向
带重定向
有办法解决这个问题吗?我错过了什么?
最佳答案
在 CORS 标准的初始定义中,不允许在成功的 CORS 预检请求后进行重定向。
IE11 实现了这个(现已过时)标准。
自 2016 年 8 月以来,这种情况发生了变化,所有主要浏览器现在都支持它(这是实际的 pull request )。
恐怕要支持<=IE11,您还必须修改服务器端代码才能不发出重定向(至少对于<=IE11)。
第 1 部分)服务器端(我在这里使用 Node.js Express):
function _isIE (request) {
let userAgent = request.headers['user-agent']
return userAgent.indexOf("MSIE ") > 0 || userAgent.indexOf("Trident/") > 0
}
router.post('data', function (request, response) {
if (_isIE(request)) {
// perform action
res.set('Content-Type', 'text/plain')
return res.status(200).send(`${redirectionTarget}`)
} else {
// perform action
response.redirect(redirectionTarget)
}
})
第 2 部分客户端
注意:这是纯 Javascript,但您可以轻松地将其调整为您的 jQuery/ajax 实现。
var isInternetExplorer = (function () {
var ua = window.navigator.userAgent
return ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0
})()
function requestResource (link, successFn, forcedRedirect) {
var http
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.XDomainRequest) {
http = new XDomainRequest()
} else {
http = new ActiveXObject("Microsoft.XMLHTTP")
}
http.onreadystatechange = function () {
var OK = 200
if (http.readyState === XMLHttpRequest.DONE) {
if (http.status === OK && successFn) {
if (isInternetExplorer && !forcedRedirect) {
return requestResource(http.responseText, successFn, true)
} else {
successFn(http.responseText)
}
}
}
}
http.onerror = http.ontimeout = function () {
console.error('An error occured requesting '+link+' (code: '+http.status+'): '+http.responseText)
}
http.open('GET', link)
http.send(null)
}
关于使用 CORS 重定向的 Ajax 请求在 IE11 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36448574/