Don't Hassle with CORS, Proxy Your Requests with This Simple Node.js Server During Web App Development

Update: After reading the comments on Reddit, I realized I should have been clearer about the context of this post. We often develop web apps against existing APIs, and during the development phase the app is running on our own servers. Since the production app will run on the same server as the API, however, it isn't worth configuring the server to deal with CORS. The technique in this post can be used a quick and easy alternative.

Sometimes web apps need to communicate via API with an external server on another domain. "What's the problem?" you may be objecting. It's 2015, after all, and CORS is already supported by all major browsers (IE8+ partial, IE10+ full support).

However, using CORS is not as simple as specifying the appropriate server URL. There are a lot of changes necessary on both the server and client tiers to get it working. I strongly recommend reading this complete CORS reference on the Mozilla Developer Network site and IE’s XDomainRequest limitations over at MSDN.

It is much simpler to proxy your HTTP requests via a server running on your domain. In fact, this can be done with just a few lines of JavaScript by combining the power of the express server library, Node.js streams and the wonderful request library:

var express = require('express');  
var request = require('request');

var app = express();  
app.use('/', function(req, res) {  
  var url = apiServerHost + req.url;
  req.pipe(request(url)).pipe(res);
});

app.listen(process.env.PORT || 3000);  

You can hook it up to whichever subpath on your server you like. One important note: don’t use bodyParser middleware on the same path, since you need the raw request body to be piped to the external server.

Jan Žák

Jan Žák

Polyglot Developer in Salsita, focused on web services, scalability and security