How to find the server port that responded to the request

4

I'm using the link to create a load balancer in NodeJS, in this module has the event  

proxy.on('proxyRes', function (res) {
  ..
});

Within this event, I would like to get the server port that answered the request by the res parameter.

EDIT

While I debug I run the res.connection.remoteAddress method, in which after I run the res.connection._peername Now I ask, is this the only correct way?

    
asked by anonymous 18.03.2014 / 21:45

1 answer

1

I do not understand if you are looking for information from the target server or local server.

If you are looking for the port used by the proxy to connect to the target server, the best way is actually using the res.connection._getpeername()

If you are looking for the port used by the client to connect to the proxy, you could use the xfwd option of the httpProxy itself to send the header x-forwarded to the target server.

So when the target server responds, you have the information in the request object.

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
    xfwd: true
});
var http = require('http');

var server = http.createServer(function(req, res) {
    proxy.web(req, res, { target: 'http://google.com/' });
});

server.listen(80);

proxy.on('proxyRes', function (res) {
    var header = res.req._headers;
    console.log(res.req.connection._getpeername());
    console.log(header['x-forwarded-port']);
});
    
25.03.2014 / 13:17