Skip to content

Instantly share code, notes, and snippets.

@davemo
Created November 6, 2012 21:56
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save davemo/4027855 to your computer and use it in GitHub Desktop.
Save davemo/4027855 to your computer and use it in GitHub Desktop.
A simple express.js server with a proxy that intercepts all requests with /api/ and proxies them to localhost:3000
var express = require('express'),
httpProxy = require('http-proxy'),
app = express();
var proxy = new httpProxy.RoutingProxy();
function apiProxy(host, port) {
return function(req, res, next) {
if(req.url.match(new RegExp('^\/api\/'))) {
proxy.proxyRequest(req, res, {host: host, port: port});
} else {
next();
}
}
}
app.configure(function() {
app.use(express.static(process.cwd() + "/generated"));
app.use(apiProxy('localhost', 3000));
app.use(express.bodyParser());
app.use(express.errorHandler());
});
module.exports = app;
@ajs139
Copy link

ajs139 commented May 31, 2018

const proxy = require('express-http-proxy');

const getPath = req => require('url').parse(req.url).path;

const createProxy = ({hostname = 'localhost', port = 80, path = ''}) =>
+  proxy(`${hostname}:${port}`, { proxyReqPathResolver: req => `${path}${getPath(req)}` });

app.use('/api', createProxy({port: 3000, path: '/api'})); // http://localhost/api/foo -> http://localhost:3000/api/foo 

@joeheyming
Copy link

thanks @ajs139 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment