简体   繁体   中英

Get response from proxy server

I created a proxy server in node.js using the node-http-proxy module.

Looks like this:

var http = require('http'),
httpProxy = require('http-proxy'),
io = require("socket.io").listen(5555);

var proxy = new httpProxy.RoutingProxy();

http.createServer(function (req, res) {
     proxy.proxyRequest(req, res, {
         host: 'localhost',
         port: 1338
     });
}).listen(9000);

So, I need, before sending the response back to the client to get the body from the server that I proxy and analyze it.

But I can't find event or attribute, where I can get this data. I tried:

proxy.on('end', function (data) {
    console.log('end');
});

But I can't figure our how to get the mime body from it.

If all you want to do is examine the response (read-only) , you could use :

proxy.on('proxyRes', function(proxyRes, req, res){

    proxyRes.on('data' , function(dataBuffer){
        var data = dataBuffer.toString('utf8');
        console.log("This is the data from target server : "+ data);
    }); 

});

But , note that the 'proxyRes' event is emitted after the response is sent.

Reference in : https://github.com/nodejitsu/node-http-proxy/issues/382

I found answer: I rewrite response function for body -

var http = require('http'),
    httpProxy = require('http-proxy'),
    io = require("socket.io").listen(5555);

var proxy = new httpProxy.RoutingProxy();

http.createServer(function (req, res) {
    console.log(req.url);
    res.oldWrite = res.write;
    res.write = function(data) {
        /* add logic for your data here */
        console.log(data.toString('UTF8'));
        res.oldWrite(data);
    }

    proxy.proxyRequest(req, res, {
        host: 'localhost',
        port: 1338
    });

}).listen(9000);

This code will console all url request and response form this endpoint.

Based on the answer of @Psycho, following code can be used to modify headers as well

var server = http.createServer(function(req, res) {

res.oldWrite = res.write;
res.write = function(data) {
    console.log(data.toString('UTF8'));
    res.oldWrite(data);
}

res.oldSetHeader = res.setHeader
res.setHeader = function(k,v) {
    console.log(k,v)
    res.oldSetHeader(k,v)
}

proxy.web(req, res, { target: proxyPool[key]}); })

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