Skip to content

Instantly share code, notes, and snippets.

@dylants
Created July 30, 2013 16:43
Show Gist options
  • Save dylants/6114665 to your computer and use it in GitHub Desktop.
Save dylants/6114665 to your computer and use it in GitHub Desktop.
simple node proxy using http-proxy
var app, routingProxy, apiProxy, proxyHost, proxyPort;
var express = require("express"),
httpProxy = require("http-proxy"),
fs = require("fs");
// Should we dynamically define these by environment?
proxyHost = "localhost";
proxyPort = "8080";
// Create and define the Express server
app = express();
// Configure a proxy to route requests that come to this Express server
// to a separate server defined by the host:port
routingProxy = new httpProxy.RoutingProxy();
// The apiProxy is created as middleware to be run within Express'
// middleware chain
apiProxy = function(pattern, host, port) {
return function(req, res, next) {
if (req.url.match(pattern)) {
routingProxy.proxyRequest(req, res, {
host: host,
port: port
});
} else {
return next();
}
};
};
// Configure the middleware for Express
app.configure(function() {
app.set("port", 3000);
app.set("views", __dirname + "/views");
app.engine('html', require('ejs').renderFile);
// use our proxy BEFORE Express' body parser to avoid hangs on POST
app.use(apiProxy(/\/api\/.*/, proxyHost, proxyPort));
app.use(express.bodyParser());
// pull in all the controllers
fs.readdirSync("controllers").forEach(function(controllerName) {
require("./controllers/" + controllerName)(app);
});
app.use(app.router);
app.use("/assets", express.static(__dirname + "/public"));
});
app.configure("development", function() {
app.use(express.errorHandler());
});
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment