Here at the SimbCo office we code for fun as often as for work. One of our team members loves comic books. He has been collecting them with his dad for about 20 years. As such he has a very extensive collection. He has been talking about finding a better way to catalog those but existing options have come up short. Luckily a solution is only a few nights and weekends of coding away.
So he found an API for a service that has an incredible amount of information regarding comics and seemed like a perfect place to start. So he started working on the interface for his application and was making great strides. But quickly ran into a road block. The application was being developed as a thick client javascript application but the server with the API doesnt allow for cross domain requests (CORS). While the final solution is to work with the API provider to enable access, that might take a while and our developer is antsy to keep moving forward.
So he asked if I had any suggestions about how we might be able to get access to the API. My immediate response was “sure its simple just setup a HTTP proxy”. Which is a great response and there is a great library for Node.js called http-proxy by Nodejitsu that will get him most of the way there.
But the default examples show doing a full proxy, which means he still needs another server to load his content. At which point our proxy and the content are running on different ports again and we are back where we started. So I put together an example below using http-proxy and express. The example will serve any requests using the static middleware first and try to fulfill any other requests via the proxy.
So if you find yourself needing to serve your static content while providing a proxy for remote content give the gist below a shot.
var express = require('express') , httpProxy = require('http-proxy') , path = require('path'); var proxy = new httpProxy.RoutingProxy(); var proxyOptions = { host: 'simb.co', port: 80 }; var app = express(); var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, Accept, Origin, Referer, User-Agent, Content-Type, Authorization'); if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }; app.configure(function() { app.use(express.static(path.join(__dirname, 'public'))); app.use(allowCrossDomain); }); app.all('/*', function (req, res) { return proxy.proxyRequest(req, res, proxyOptions); }); app.listen(3333);
You can see a running example here or checkout our StaticHttpProxyExample example on github.