Created
November 6, 2012 21:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
thanks @ajs139 🎉
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your gist
Here is my update written in ES6 with new version of node proxy > https://gist.github.com/gouroujo/a5d7d5582128d099cbfc5e826c55e311