我正在尝试学习node.js,我的上下文是来自nodejitsu的http-proxy模块。
我想访问代理事件的结尾,以便我可以记录目标服务器响应的时间。但是,我不知道如何创建适当的回调或事件处理程序。我查看了http-proxy的源代码,它似乎没有采用传统的回调方法。
以下是一个示例,我确信它是对呼吸节点的人的一个简单修复:
/* demonstrate a basic proxy server that can log the time
it takes to execute a given hit on the destination server
*/
var http = require('http'),
httpProxy = require('http-proxy');
// Create the proxy server
httpProxy.createServer(function (req, res, proxy) {
var startTime = ( new Date()).getTime();
// NEED HELP HERE.
// something like this should do it?
proxy.addListener("end",function() {
var endTime = (new Date()).getTime();
console.log("request took " + (endTime - startTime) + "ms");
});
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9000
});
}).listen(8000);
// the destination server
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
// make the hit slow by pausing the end()
setTimeout(function() {
res.end();
},2000);
}).listen(9000);
答案 0 :(得分:3)
一种方法是拦截res.end()调用。我有3天的快递经验,所以我不知道这会搞砸了什么:
var proxy = new httpProxy.RoutingProxy();
app.get("/foo", function (req, res) {
var realEnd = res.end;
var start = +new Date();
res.end = function () {
var elapsed = +new Date() - start;
console.log("elapsed", elapsed);
realEnd.apply(res);
}
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9000
});
});