0

I wanted to proxy a call to new port so I encapsulate all the logic of create server to a function like

var appRouter = express.Router();
app.use(appRouter);


appRouter.route('*')
    .get(function (req, res) {
        proxyRequest(req, res)
    }

in the proxy request function I put the following code

function proxyRequest(req, res) {

    httpProxy = require('http-proxy');
    var proxy = httpProxy.createProxyServer({});
    var hostname = req.headers.host.split(":")[0];

    proxy.web(req, res, {
        target: 'http://' + hostname + ':' + 5000
    });
    http.createServer(function (req, res) {
        console.log("App proxy new port is: " + 5000)
        res.end("Request received on " + 5000);
    }).listen(5000);

}

The problem is that when I do the first call I saw that the proxy is working fine and listen in new server port 5000 when I hit the browser for the second time I got error

Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1146:14)

How should I avoid this

Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
07_05_GuyT
  • 2,787
  • 14
  • 43
  • 88
  • I'm no node expert, but it sounds like you're launching the server twice. – Evan Knowles Jul 07 '15 at 09:55
  • @EvanKnowles-Correct but how should I avoid it in elegant way since I need to do it just one time and when I have additional call to this port I want just to route the call to the new server port... – 07_05_GuyT Jul 07 '15 at 09:57
  • looks like you are trying to create a proxy server on every request. See the example [here](http://stackoverflow.com/a/31257399/1807881) – hassansin Jul 07 '15 at 10:01
  • @hassansin-thanks but this is not the case the example you provided is very simple, in my app I put it in a function and every time that you run get method this is invoked,there is a way to avoid it?if i created new server in the second call I just want to route it to the new server with the new port... – 07_05_GuyT Jul 07 '15 at 10:21

1 Answers1

1

Remove proxy server creation logic from proxyRequest function

Try this:

httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
http.createServer(function (req, res) {
    console.log("App proxy new port is: " + 5000)
    res.end("Request received on " + 5000);
}).listen(5000);

function proxyRequest(req, res) {
  var hostname = req.headers.host.split(":")[0];
  proxy.web(req, res, {
    target: 'http://' + hostname + ':' + 5000
  });    
}
hassansin
  • 16,918
  • 3
  • 43
  • 49