在IE11中,使用CORS重定向的Ajax请求失败

rob*_*son 5 ajax redirect cors

我正在尝试向同一域上的资源发出ajax请求.在某些情况下,请求被重定向(303)到外部资源.外部资源支持CORS.

在Chrome,Firefox或Safari等浏览器中,请求成功.
在IE11中,请求失败并显示错误:

SCRIPT 7002: XMLHttpRequest: Network Error 0x4c7, The operation was canceled by the user
Run Code Online (Sandbox Code Playgroud)

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');
});
Run Code Online (Sandbox Code Playgroud)

我已经构建了一个演示问题的小例子.你可以在这里看到代码.

没有重定向

没有重定向

w /重定向

w /重定向

有没有办法解决这个问题?我错过了什么?

小智 4

在 CORS 标准的初始定义中,不允许在成功的 CORS 预检请求后进行重定向。

IE11 实现了这个(现已过时)标准。

自 2016 年 8 月以来,这种情况发生了变化,所有主要浏览器现在都支持它(这是实际的拉取请求)。

恐怕要支持<=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)
  }
})
Run Code Online (Sandbox Code Playgroud)

第 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)
}
Run Code Online (Sandbox Code Playgroud)