2015-12-02 134 views
2

我不知道node.js request模塊如何在timeout參數方面工作。node.js請求中的超時

timeout時間過後會發生什麼?即:

var request = require('request'); 
var options = { 
    url: Theurl, 
    timeout: 300000 
}; 

request(options, function(error, resp, body) {... 

300000後會發生什麼?請求是否嘗試再次請求網址?

我還發現,Linux Kernel有一個默認的20秒TCP socket connection timeout.http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout) 這是否意味着在requesttimeout選項將最多20秒(如果我不改變​​),無論我在options設置?我使用Ubuntu

回答

1

request返回錯誤,錯誤代碼如request自述文件(超時段)中所述設置。

查看TIME_WAIT的詳細信息。

但是,內核會通過配置將其削減。如鏈接所述,您可以通過鏈接tcp_syn_retries來更改它。

1

從請求包的自述:

Note that if the underlying TCP connection cannot be established, 
the OS-wide TCP connection timeout will overrule the timeout option 

所以你的情況,請求將被中止後的20秒。該請求不會嘗試再次請求URL(即使超時設置爲低於20000的值)。您必須爲此編寫自己的邏輯或使用其他程序包,例如requestretry

例子:

var options = { 
    url: 'http://www.gooooerererere.com/', 
    timeout: 5000 
} 

var maxRequests = 5; 

function requestWithTimeout(attempt){ 
    request(options, function(error,response,body){ 
     if(error){ 
      console.log(error); 

      if(attempt==maxRequests) 
       return; 
      else 
       requestWithTimeout(attempt+1); 
     } 
     else { 
      //do something with result 
     } 
    }); 
} 

requestWithTimeout(1); 

您還可以檢查特定的錯誤信息,如ETIMEDOUT,與

if(error.code == [ERROR_MESSAGE]) 
+0

好的,謝謝,但你怎麼說賴特我自己的邏輯? – user1665355

+0

您可以等待錯誤(請求超時)並再次進行呼叫。讓我知道你是否需要一個例子。 – piscator

+0

好的。是的,請舉個例子,它會很親切!然後我可以接受它作爲答案。 – user1665355

0

如果發生超時,你的回調函數會被錯誤執行的設定信息'錯誤:ETIMEDOUT'。

這個小項目https://github.com/FGRibreau/node-request-retry提供了隨時可用的配置包裝,使重試由許多連接錯誤代碼觸發,包括超時。

+0

好吧,是否有可能重試,直到'request'成功? – user1665355

+0

看看這個項目:[鏈接](https://github.com/FGRibreau/node-request-retry)。它是一個請求包裝器,在最終放棄之前配置重試延遲和重試次數。 –

+0

謝謝!將退房 – user1665355