2013-06-18 53 views
5

我在node.js上使用http-proxy。我有一個代理請求到另一臺服務器。我的要求是代理請求應該在10秒內超時。而且,當超時發生時,我應該能夠顯示自定義消息向用戶node.js http-proxy如何根據請求設置超時和處理程序

我有下面的代碼

var proxy = new httpProxy.RoutingProxy(); 
    req.on('error', function (err,req,res){ 
     res.send("An error occured"); 
    }); 
    proxy.proxyRequest(req, res, { 
    host: 'localhost', 
    port: port, 
    headers:req.headers, 
    timeout:10000 
    }) 

這設定的超時時間(由於未知的原因,它超時在17秒),但回調永遠不會執行。它只是顯示了標準的瀏覽器消息提前

The connection was reset 
      The connection to the server was reset while the page was loading. 

感謝

UPDATE

我試圖

proxy.on('proxyError', function (err,preq,pres) { 
    pres.writeHead(500, { 'Content-Type': 'text/plain' }); 
    pres.write("An error happened at server. Please contact your administrator."); 
    pres.end(); 
    }); 

這一次的方法被調用,但抱怨說,響應已發送,因此無法設置標題

回答

2

您可能想試試這個:

proxy.on('error', function(err, preq, pres){  
    pres.writeHead(500, { 'Content-Type': 'text/plain' }); 
    pres.write("An error happened at server. Please contact your administrator."); 
    pres.end(); 
});