[英]node.js proxied request body
我有一个简单的问题,使用node.js
和node-http-proxy
获取双重代理请求的响应主体。
我基本上想做的是在Chrome中将服务器的IP和端口设置为代理(有效),然后将请求代理到另一台服务器。
这是我的方法:
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)
不幸的是,这里没有任何“关于数据”事件对我有用……“结束”事件对我来说没什么用,但是我从未设法弄清尸体。 有谁知道如何实现这一目标? 我需要将每个请求的正文保存到特定文件中。
是的...这不在我的头上。 请注意,由于大多数网站都在端口80上提供服务,因此我代理了端口80。请为您的特定用例更改代码。 这在CoffeeScript中。
日志请求标头:
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)
在浏览器代理中输入“ localhost”和端口8080。 这对您有用吗?
日志请求正文:
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)
我对此进行了测试,并可以确认它记录了POST / PUT的正文。
日志响应正文:
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)
可能不是最干净的方法,但我可以确认它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.