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
.
Last active
August 29, 2015 14:25
-
-
Save jonstorer/b3b0d92d4e70645af33a to your computer and use it in GitHub Desktop.
node.js request proxy
This file contains hidden or 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 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; |
This file contains hidden or 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 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