简体   繁体   English

Internet Explorer <= 9 中的 AngularJS $http.post 错误

[英]AngularJS $http.post error in Internet Explorer <= 9

I have the following bit of code, which works fine in every modern browser, but fails in Internet Explorer 9 and below.我有以下代码,在每个现代浏览器中都可以正常工作,但在 Internet Explorer 9 及以下版本中失败。

authService.login = function(credentials) {
  return $http.post('https://example.com/login', credentials).then(function(res) {
    return res;
  }, function(err) {
    return err;
  });
};

credentials is an object that looks like this: credentials是一个看起来像这样的对象:

{
  username: 'john@example.com',
  password: 'smith'
}

The problem is that the POST never actually happens, instead it jumps straight to return err;问题是 POST 从未真正发生过,而是直接跳转return err; and no error is even set.甚至没有设置错误。 It says Impossible d'effectuer l'opération à cause de l'erreur suivante c00c023e.上面写着Impossible d'effectuer l'opération à cause de l'erreur suivante c00c023e. . . The key being c00c023e , which is supposedly an encoding problem, but I don't see how that would completely prevent the call from happening.关键是c00c023e ,这应该是一个编码问题,但我看不出这将如何完全阻止调用的发生。

The 'fix' is to use $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; “修复”是使用$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; which does allow IE to POST, but my backend expects JSON so that doesn't help.这确实允许 IE 发布,但我的后端需要 JSON,所以这无济于事。

I'm using AngularJS 1.2.22.我正在使用 AngularJS 1.2.22。

Any ideas?有任何想法吗?

Comments led me in the right direction, this was indeed a CORS issue.评论使我朝着正确的方向前进,这确实是一个 CORS 问题。 Turns out there is a simple and library agnostic fix provided by the XDomain library .结果发现XDomain 库提供了一个简单且与库无关的修复程序。

In the app making the CORS request, include the following script before any other scripts:在发出 CORS 请求的应用程序中,任何其他脚本之前包含以下脚本:

<!--[if lte IE 9]>
    <script src="http://example.com/xdomain/xdomain.min.js" data-slave="http://example.com/xdomain/proxy.html"></script>
<![endif]-->

Then, on the example.com domain, copy xdomain.min.js and create the proxy.html file that was defined above in the data-slave attribute.然后,在example.com域上,复制xdomain.min.js并创建上面在data-slave属性中定义的proxy.html文件。 The proxy file must contain:代理文件必须包含:

<!DOCTYPE html>
<script src="xdomain.min.js" data-master="https://subdomain.example.com"></script>

Cross-domain requests will now work properly in IE9 and below.跨域请求现在可以在 IE9 及更低版本中正常工作。 You could use XDomain for every browser rather than just IE by removing the conditional comment, but I doubt there is a significant portion of users using a browser that doesn't support CORS that also isn't Internet Explorer.您可以通过删除条件注释将 XDomain 用于每个浏览器,而不仅仅是 IE,但我怀疑有很大一部分用户使用不支持 CORS 的浏览器,也不是 Internet Explorer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM