javascript - How to set up a reverse proxy in nodejs for multiple targets? -
i using nodejs, expressjs , request create reverse proxy.
what want when request sent http://localhost:port/name/ corresponding page loaded.
for example, if enter http://localhost:1234/google/ google website loaded , if enter http://localhost:1234/stack/ stackoverflow page loaded instead.
i tried code similar 1 here
var request = require('request'); app.get('/google', function(req,res) { //modify url in way want var newurl = 'http://google.com/'; request(newurl).pipe(res); });
the problem is, loads pages, not completely, since pages wanna load images , css , stuff , make requests /images/example.jpg , end 404 error.
has handy solution problem? since setting route /images no good, sincei have 2 possible target servers , proxy wouldn't know right one.
first of all, forward proxy, second, here working code of want, modify please
call http://127.0.0.1:5432/yahoo.com
var request = require('request'); var express = require('express')(); var session = require('cookie-session'); express.set('trust proxy', 1) express.use(session({ keys: ['key1', 'key2'] })) express.use(function(req,res,next) { if(req.url.indexof('.com') < 0) { request('http://'+req.session.domain+'/'+req.params.site,function(err,response,body) { if(err) res.status(500).send(err); else res.send(body); }); } else next(); }); express.get('/:site',function(req,res) { request('http://'+req.params.site,function(err,response,body) { req.session.domain = req.params.site; if(err) res.status(500).send(err); else res.send(body); }); }); express.listen(5432);
Comments
Post a Comment