简体   繁体   中英

Node.js proxy for monitor network requests and responses

I am using Nodejitsu's http proxy to build a tool to monitor web traffic.

httpProxy.createProxyServer({
    target: 'http://localhost:9000'
})
.listen(8000);

util.puts('proxy server listening on port 8000');


http.createServer(function targetServer(req, res) {
    res.writeHead(302, { 'Location': req.headers.host });
    util.puts('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));

    res.end();

})
.listen(9000);

util.puts('target server listening on port 9000');

What I want to do is

  1. Proxy outgoing requests from the client (browser) to my target server
  2. Send them to their original destination url from my target server
  3. Receive the response on my target server
  4. Send the response back to the client

Basically have a middleman placed between the client and the destination server so i can monitor traffic. However when I try to do this, as soon as I make the 302 request, I get an ECONN error.

Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

Can anyone help me figure out whats going on

UPDATE

I changed the 302 Location argument like so:

res.writeHead(302, { 'Location': '/' });

Now, when the browser tries hitting my proxy server, it enters a redirection loop. Why is this happening?

If you are going to replace dns queries by your server ip of your proxy it is possible - only works when not ssl, due to invalid certificate for every domain. Otherwise I don't have any clue how it should work. Here is an example:

const httpProxy = require('http-proxy');
const http = require('http');

var proxy = httpProxy.createProxyServer();

var server = http.createServer(function(req, res) {
    proxy.web(req, res, {
        target: 'http://' + req.headers.host + req.url
    });
    console.log('Yay, got it routed through my proxy.');
    console.log(req.connection.remoteAddress + '--->' + req.headers.host);
});

proxy.on('end', function(req, res) {
    console.log(req.connection.remoteAddress + '<---' + req.headers.host);
    // Do some nasty tracking and monitoring
});

server.listen(8000);

Dns queries must point to this server if you are trying to monitor outgoing requests.

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