Fix IE8+ CORS requests using Node.js

As a web developer usually we have to deal with that beloved browser that everyone likes: Internet Explorer. I have to admit that Microsoft are working hard to clean its past with the recent IE versions. However, even with the end of the Windows XP support, there are still a lot of people using old IE versions like IE8.

In several projects I had to guarantee the backwards compatibility with IE. This is hard, but it’s harder if your application needs to send AJAX requests to remote hosts. This is known as CORS (Cross-Origin Resources Sharing). Modern browsers have absolute no problems handling these requests but old IE versions have compatibility issues.

When I have to deal with CORS in IE, I usually am using jQuery and I’m able to use some plugin. For example, the MoonScript’s plugin gave me good results several times. The inconvenience with this solution is that requires to do a lot of tests in different browsers.

In my last project I wanted to try something different. I was developing an AngularJS application with Node.js in the backend. So I wondered: what if I leave Node.js make the CORS requests for me?. Node.js variety of modules give us the possibility to build a fast and robust server with the latest technologies. For that reason, if you are using Node.js to serve your pages, instead of make the CORS request from your application you just send to Node.js the information of where have to send the data. Notice that the request sent from IE to Node.js is a local request. IE CORS problems no more!

There are infinite ways to do this. I’m going to give you what worked for me. I’m assuming you have a Node.js server (obviously) with Express 4 routing the requests. I’m going to use a module called request.

var request = require('request');

router.route('/mirror_proxy/post').post(function(req, res) {
  var url = req.body.url;
  var data = req.body.data;

  request.post({url: url, form: data}, function(err, httpResponse, body) {
     if (err) {
          return console.error('request failed:', err);
     }
     console.log('Server responded with:', body);
     res.send(body);
  });
});

Obviously this is just a fragment of code. That “router” variable must be passed to Express and the Node.js server be initialized. For more information about how to do this, check the complete code in GitHub.

So that’s all! Just a few lines of code and the big IE CORS problem is completely nonexistent.

Good coding!

Leave a Reply

Your email address will not be published. Required fields are marked *