Skip to content

Instantly share code, notes, and snippets.

@mboersma
Created June 5, 2012 22:03
Show Gist options
  • Save mboersma/2878351 to your computer and use it in GitHub Desktop.
Save mboersma/2878351 to your computer and use it in GitHub Desktop.
node-http-proxy example
var url = require('url'),
http = require('http'),
nodeStatic = require('node-static'),
httpProxy = require('http-proxy');
// create node-http-proxy instance
var proxy = new httpProxy.HttpProxy({
target: {
host: 'localhost',
port: 9000
}
});
var fileServer = new nodeStatic.Server('./public');
var apiRegex = /^\/api\//;
// create http server
var server = http.createServer(function (request, response) {
// QUESTION: is there any way to detect HTTP vs. HTTPS inside this function?
// We want to create a
// parse url for regex matching
var url_parts = url.parse(request.url);
console.log(url_parts.protocol);
// if it's an API request, proxy it.
if (apiRegex.test(url_parts.pathname)) {
return proxy.proxyRequest(request, response);
// otherwise let the static file server handle the request
} else {
request.addListener('end', function () {
fileServer.serve(request, response, function(err, result) {
// respond with the index page if no route was found
if (err && (err.status === 404)) {
fileServer.serveFile('/index.html', 200, {}, request, response);
}
});
});
};
});
server.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment