Skip to content

Instantly share code, notes, and snippets.

@davemo
Created November 6, 2012 21:56
Show Gist options
  • 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;
@toddhgardner
Copy link

Thanks for this, was helpful!

@paulomcnally
Copy link

Whats is the version from http-proxy?

httpProxy.RoutingProxy => undefined

@dbuezas
Copy link

dbuezas commented Sep 17, 2015

v0.10.4

@mchavarriae
Copy link

This doesn't work for put/post for me, any idea?

@gouroujo
Copy link

gouroujo commented Jun 21, 2016

Thanks for your gist
Here is my update written in ES6 with new version of node proxy > https://gist.github.com/gouroujo/a5d7d5582128d099cbfc5e826c55e311

@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