Skip to content

Instantly share code, notes, and snippets.

@jonstorer
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonstorer/b3b0d92d4e70645af33a to your computer and use it in GitHub Desktop.
Save jonstorer/b3b0d92d4e70645af33a to your computer and use it in GitHub Desktop.
node.js request proxy

This original request http://web.com/api/v1/resources hits the /api namespace and is sent to the proxy.js app. The proxy.js app recieves /v1/resources and uses that to build the new request to http:/api.com/v1/resources.

var url = require('url')
, request = require('request');
var buildUrl, proxy;
buildUrl = function (url) {
var newUrl, currentUrl;
currentUrl = url.parse(url);
newUrl = url.parse('https://myotherdomain.com/');
newUrl.pathname = currentUrl.pathname;
newUrl.search = '?' + currentUrl.query;
return url.format(newUrl);
}
proxy = require('express')();
proxy.all('*', function (req, res, next) {
// take the original request
// pipe it into a new request with a new url
// pipe the new request's response into the original response
req.pipe(request(buildUrl(req.url))).pipe(res);
}
module.exports = proxy;
var app = require('express')();
app.all('/api', require('./proxy'));
app.get('/', function (req, res, next) {
res.send('use the /api namespace to make api calls');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment