2012-01-01 34 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 
    }); 
});