[英]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.