Node.js proxy request body

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

What I'm basically trying to do is set the IP address and port of my server in Chrome as a proxy server (which works), which then proxies the request to another 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 "according to data" events work for me here ... There are "events" of the end, but I still could not get the bodies. Does anyone know how to achieve this? I need to save the body of each request to a specific file.

0
source share
1 answer

Yes ... it's not in my head. Please note that I am connecting to port 80 as most websites serve port 80. Change the code for your specific use case. This is in CoffeeScript.

Magazine 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 proxy server. 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 checked this and can confirm that it registers the body of the 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) 

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

+1
source

Source: https://habr.com/ru/post/1484919/


All Articles