Tom
Tom

Reputation: 1701

node.js proxied request body

I am having a simple problem getting the response body of a double proxied request using node.js and node-http-proxy.

What I am basically trying to do, is to set the IP and port of my server in Chrome as a proxy (which works), which will then proxy the request to an other server.

Here is how I do it :

var ip = {'xx.xx.xx.xx', 8080};

var proxy = new httpProxy.HttpProxy({ 
    target: {
        port : ip[0], host : ip[1]
    }
});

var server = http.createServer(function(req, res) {
    proxy.proxyRequest(req, res);
    proxy.on('data', function() { console.log(data);});
}).listen(8001)

Unfortunately, none of the "on data" events are working for me here... The "end" events are, but I never managed to get the bodies. Does anyone know how to achieve this ? I need to save the body of each requests to a specific file.

Upvotes: 0

Views: 4000

Answers (1)

JP Richardson
JP Richardson

Reputation: 39375

Yes... this is off the top of my head. Note, that I'm proxying to port 80 since most websites serve on port 80. Change the code for your specific use case. This is in CoffeeScript.

Log Request Headers:

fs = require('fs')
httpProxy = require('http-proxy')

fsw = fs.createWriteStream('myfile.txt', flags: 'a', mode: 0666, encoding: 'utf8')
server = httpProxy.createServer  (req, res, proxy) ->
           req.connection.pipe(fsw) #runs in parallel with the proxy... don't you love Node.js?
           proxy.proxyRequest(req, res, {
             host: require('url').parse(req.url).hostname,
             port: 80
           })
server.listen(8080)

JS Translation

Put 'localhost' and port 8080 for your browser proxy. Does this work for you?

Log Request Body:

fs = require('fs')
httpProxy = require('http-proxy')


server = httpProxy.createServer  (req, res, proxy) ->
           body = ''
           req.on 'data', (chunk) ->
             body += chunk

           req.on 'end', ->
             fs.writeFile('mybody.txt', body, 'utf8')

           proxy.proxyRequest(req, res, {
             host: require('url').parse(req.url).hostname,
             port: 80
           })
server.listen(8080)

I tested this and can confirm that it logs the body of a POST/PUT.

Log Response Body:

fsw = fs.createWriteStream('myfile.txt', flags: 'a', mode: 0666, encoding: 'utf8')
server = httpProxy.createServer  (req, res, proxy) ->
  oldwrite = res.write
  res.write = (data, encoding, fd) ->
    fsw.write(data)
    res.write = oldwrite
    res.write(data, encoding, fd)
    res.write = oldwrite #<--- patch again before we leave the method


  proxy.proxyRequest(req, res, {
    host: require('url').parse(req.url).hostname,
    port: 80
  })

server.listen(8080)

Might not be the cleanest way, but I can confirm that it works.

Upvotes: 1

Related Questions