Search code examples
angularjsinternet-explorerxdomainrequest

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.

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:

{
  username: '[email protected]',
  password: 'smith'
}

The problem is that the POST never actually happens, instead it jumps straight to return err; and no error is even set. It says 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.

The 'fix' is to use $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.

I'm using AngularJS 1.2.22.

Any ideas?


Solution

  • Comments led me in the right direction, this was indeed a CORS issue. Turns out there is a simple and library agnostic fix provided by the XDomain library.

    In the app making the CORS request, include the following script before any other scripts:

    <!--[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. 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. 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.