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

时间:2016-04-06 10:37:29

标签: ajax redirect cors

我试图向同一域上的资源发出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

没有重定向

w/o redirect

w / redirect

w/ redirect

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

2 个答案:

答案 0 :(得分:4)

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

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

自2016年8月以来,这已发生变化,现在所有主要浏览器都支持它(这是实际的pull request)。

我害怕支持< = IE11你必须修改你的服务器端代码以及不发出重定向(至少对于< = IE11)。

第1部分)服务器端(我在这里使用node.js表示):

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)
}

答案 1 :(得分:-2)