简体   繁体   English

Node.js和https证书错误处理

[英]Node.js and https certificate error handling

To make a long story short: 使长话短说:

I'm building node app which making a request with https (the secure version of http). 我正在构建节点应用程序,该应用程序使用https (HTTP的安全版本)发出请求。 Whenever I miss-configure my request options, I'm having this error: 每当我错过配置请求选项时,就会出现此错误:

Node.js Hostname/IP doesn't match certificate's altnames Node.js主机名/ IP与证书的altname不匹配

Great... except of the fact that the entire request code is wrapped with a valid try..catch block (which works just fine.. checked that already). 很好...除了整个请求代码都包装有有效的try..catch (工作正常,已经检查过)之外。 The code is basically something like this: 代码基本上是这样的:

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
}

What I intend to do is to simply handle that error within my try..catch block 我打算做的只是在try..catch块中处理该错误。

After reading some posts I've learned that this behavior is mainly because the tls module is automatically process the request and therefore making this error - this is a nice piece of information but it doesn't really help me to handle the exception. 阅读一些帖子后,我了解到这种行为主要是因为tls模块自动处理请求并因此产生此错误-这是一条很好的信息,但是它并不能真正帮助我处理异常。

Some other suggested to use this option: 建议其他一些人使用此选项:

rejectUnauthorized: false // BEWARE: security hazard!

But I rather not... so.. I guess my questions are: 但是我宁愿不...所以..我想我的问题是:

  1. Handling an error with a try..catch block should work here..right? 使用try..catch块处理错误应该在这里..对吗?
  2. If not - is this behavior is by-design in node? 如果不是,此行为是节点设计的吗?
  3. Can I wrap the code in any other way to handle this error? 我可以用其他任何方式包装代码来处理此错误吗?

Just to be clear - I'm not using any third-party lib (so there is no one to blame) 只是要清楚一点-我没有使用任何第三方库(所以没有人要责怪)

Any kind of help will be appreciated 任何帮助将不胜感激

Thanks 谢谢

You need to add an 'error' event handler on the request object returned by https.request() to handle that kind of error. 您需要在https.request()返回的请求对象上添加'error'事件处理程序,以处理此类错误。 For example: 例如:

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

See this section in the node.js documentation about errors for more information. 有关更多信息,请参见node.js文档中有关错误的本节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM