2012-01-01 61 views
0

我想学习node.js,并且我的上下文是来自nodejitsu的http代理模块。node.js,http代理请求结束时的回调?

我想访问代理事件的结束,以便我可以记录目标服务器响应多长时间。但是,我不能解决如何创建适当的回调或事件处理程序。我查看了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); 

回答

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 
    }); 
});