2017-02-16 223 views
0

爲了使長話短說:的Node.js和HTTPS證書錯誤處理

我建立其提出請求與HTTPS(HTTP的安全版本)節點的應用程序。每當我想念-配置我的請求選項,我有這樣的錯誤:

Node.js Hostname/IP doesn't match certificate's altnames

大......除了那整個請求的代碼是包裹着一個有效的try..catch(工作就好了事實..已經檢查)。該代碼基本上是這樣的:

try 
{ 
    https.request(options, (response) => 
    { 
     // no way I making it so far this that error 

    }).end(); 
} 
catch(ex) 
{ 
    // for some reason.. I'm not able to get here either 
} 

我打算做的是簡單地處理我的try..catch

內的錯誤讀一些職位我學會後,這種行爲主要是因爲tls模塊會自動處理請求並因此發生此錯誤 - 這是一條很好的信息,但它並不能幫助我處理異常。

其他一些建議使用此選項:

rejectUnauthorized: false // BEWARE: security hazard! 

但我寧願不...所以...我想我的問題是:

  1. 處理錯誤與try..catch塊應該工作here..right?
  2. 如果不是 - 這種行爲是否在節點設計?
  3. 我可以用任何其他方式包裝代碼來處理這個錯誤嗎?

只是要清楚 - 我沒有使用任何第三方的LIB(所以沒有人責怪)

任何形式的幫助將不勝感激

感謝

回答

0

您需要在由https.request()返回的請求對象上添加一個'error'事件處理程序來處理這種錯誤。例如:

var req = https.request(options, (response) => { 
    // ... 
}); 
req.on('error', (err) => { 
    console.log('request error', err); 
}); 
req.end(); 

請參閱this section in the node.js documentation about errors瞭解更多信息。

+0

man ..我把'.on('error'handler')附加到...響應:(太晚了 - 要睡覺了!謝謝你的洞察! – ymz