简体   繁体   中英

Implementing Reverse Proxy in Nodejs

I am trying to create a reverse proxy using nodejs , where i could map different ombinations to point to various websites.

The follwing is my first attempt code:

var http = require('http'),
httpProxy = require('http-proxy');
httpProxy.createServer(function (req, res, proxy) {
  proxy.proxyRequest(req, res, {
  host: 'www.yahoo.com',
  port: 80
 });
}).listen(8000);

well works fine , but if i have a whole set of combinations . i dunno how to go about doing so.

My Second attempt

var http = require('http'),
httpProxy = require('http-proxy');

var mapping = {
hostnameOnly: true ,
router : {
 '127.0.0.1:8000' : 'www.google.com' ,
 '127.0.0.1:8001' : 'www.yahoo.com'
   }
}

var proxyserver = httpProxy.createServer(mapping).listen (80) ;

This doest even work , i dunno why .

Well all i am trying to create is simple application where i map to domains and fetch those pages. I am still getting a hang of nodejs , so i apologies if the question sounds ridiculous.

Your second attempt fails because the hostnameOnly specification does not accept ports in the routing paths. From the node-http-proxy docs :

var options = {
  hostnameOnly: true,
  router: {
    'foo.com': '127.0.0.1:8001',
    'bar.com': '127.0.0.1:8002'
  }
}

You're on the right track though. See here . It should work fine if you omit the hostnameOnly argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM