http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.93k stars 1.97k forks source link

how to proxy to a host with the variable target DEPENDING on the data received in the req? #907

Open macscripter opened 8 years ago

macscripter commented 8 years ago

Hi, I need to use this library to proxy to a host with the variable target DEPENDING on the data received in the req, let's suppose that I need to find a tag and basing on this tag route to a host. My code is:

var http = require('http'), httpProxy = require('http-proxy'), proxy = httpProxy.createProxyServer({});
var miTarget='web:CountryName'; var inicio = '<'+miTarget+'>'; var fin = '</'+miTarget+'>';

var server = http.createServer(function(req, res) { var miTag = ''; req.on('data', function (data) { miTag = data.toString().split(inicio)[1].split(fin)[0]; });

  req.on('end', function () {
  console.log('miTag!!!!!!:'+miTag);
  if(miTag=='Portugal') {
  proxy.web(req, res, {target: 'http://www.webservicex.net'}); 
  }
  else { 
  proxy.web(req, res, {target: 'http://localhost:1337'}); 
  }

  });    

});

console.log("listening on port 80") server.listen(80);

This code is not working... Can anyone help me? The most important for me is to execute thie proxy.web() AFTER the data is received miTag in the req...

Thanks in advance!

Best

macscripter commented 8 years ago

When in req.on('data') or req.on('end') I call proxy.web() I never receive any response but when I execute proxy.web OUT of the req.on('data') or req.on('end') everything is working well but as the req.on('data') is async I will not get the miTag before to execute proxy.web......

So I really need to put the proxy.web to be executed withing the req.on('data') or req.on('end') since depending on the miTag variable received from the data I will proxy to a different server. How can I sort out this problem?

Thank you!

ChrisBrandhorst commented 8 years ago

I am looking for a similar solution. I have found that if I put the proxy.web() into the req.on('data'), the following error occurs:

/Users/chris/Code/kodi-json-rpc/node_modules/http-proxy/lib/http-proxy/index.js:119
    throw err;
          ^
Error: socket hang up
    at createHangUpError (_http_client.js:215:15)
    at Socket.socketCloseListener (_http_client.js:247:23)
    at Socket.emit (events.js:129:20)
    at TCP.close (net.js:485:12)