2017-02-16 221 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