我正在使用node-http-proxy。但是,除了中继HTTP请求之外,我还需要监听传入和传出数据。
截取响应数据是我正在努力的地方。Node的ServerResponse对象(更通用的是WritableStream接口)不广播'data'事件。http-proxy似乎创建了自己的内部请求,这会生成一个ClientResponse对象(它确实会广播'data'事件),但是该对象不会在代理外部公开。
有什么想法可以在不修补node-http-proxy或者在响应对象周围创建包装器的情况下解决这个问题吗?
发布于 2012-03-23 00:41:39
在Github上的node-http-proxy问题中的相关问题似乎暗示这是不可能的。对于其他人未来的尝试,我是如何解决这个问题的:
res objectwriteHead()、write()和end()方法。由于res已经是EventEmitter,因此您可以开始为这些新事件发出新的自定义事件,以组合响应数据,然后使用它var eventifyResponse = function(res) {
var methods = ['writeHead', 'write', 'end'];
methods.forEach(function(method){
var oldMethod = res[method]; // remember original method
res[method] = function() { // replace with a wrapper
oldMethod.apply(this, arguments); // call original method
arguments = Array.prototype.slice.call(arguments, 0);
arguments.unshift("method_" + method);
this.emit.apply(this, arguments); // broadcast the event
};
});
};
res = eventifyResponse(res), outputData = '';
res.on('method_writeHead', function(statusCode, headers) { saveHeaders(); });
res.on('method_write', function(data) { outputData += data; });
res.on('method_end', function(data) { use_data(outputData + data); });
proxy.proxyRequest(req, res, options)发布于 2015-08-24 23:36:02
这是一个简单的代理服务器,嗅探流量并将其写入控制台:
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
// assign events
proxy.on('proxyRes', function (proxyRes, req, res) {
// collect response data
var proxyResData='';
proxyRes.on('data', function (chunk) {
proxyResData +=chunk;
});
proxyRes.on('end',function () {
var snifferData =
{
request:{
data:req.body,
headers:req.headers,
url:req.url,
method:req.method},
response:{
data:proxyResData,
headers:proxyRes.headers,
statusCode:proxyRes.statusCode}
};
console.log(snifferData);
});
// console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
// collect request data
req.body='';
req.on('data', function (chunk) {
req.body +=chunk;
});
req.on('end', function () {
});
});
proxy.on('error',
function(err)
{
console.error(err);
});
// run the proxy server
var server = http.createServer(function(req, res) {
// every time a request comes proxy it:
proxy.web(req, res, {
target: 'http://localhost:4444'
});
});
console.log("listening on port 5556")
server.listen(5556);发布于 2013-08-28 22:38:35
我试过你的方法,但对我不起作用。我的用例很简单:我想要记录从Android应用程序到我们的临时服务器的进出流量,这是由基本身份验证保护的。
https://github.com/greim/hoxy/
是我的解决方案。我的node-http-proxy总是返回500 (而对stage的直接请求没有)。也许authorization报头不会被正确转发或其他什么。
Hoxy从一开始就工作得很好。
npm install hoxy [-g]
hoxy --port=<local-port> --stage=<your stage host>:<port>作为我指定的日志记录规则:
request: $aurl.log()
request: @log-headers()
request: $method.log()
request: $request-body.log()
response: $url.log()
response: $status-code.log()
response: $response-body.log()注意,这会打印任何二进制内容。
https://stackoverflow.com/questions/9741607
复制相似问题