gpt4 book ai didi

javascript - Node.js 和 https 证书错误处理

转载 作者:行者123 更新时间:2023-12-03 04:59:40 25 4
gpt4 key购买 nike

长话短说:

我正在构建使用 https (http 的安全版本)发出请求的 Node 应用程序。每当我错过配置请求选项时,就会遇到此错误:

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

太棒了......除了整个请求代码都用有效的try..catch block 包装(它工作得很好......检查已经)。代码基本上是这样的:

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 block 中处理该错误

在阅读了一些帖子后,我了解到这种行为主要是因为 tls 模块自动处理请求,因此出现此错误 - 这是一条很好的信息,但它并不真的帮助我处理异常。

其他一些人建议使用此选项:

rejectUnauthorized: false // BEWARE: security hazard!

但我宁愿不...所以..我想我的问题是:

  1. 使用 try..catch block 处理错误应该可以在这里工作......对吗?
  2. 如果不是 - 此行为是 Node 中的设计使然吗?
  3. 我可以用其他方式包装代码来处理此错误吗?

需要明确的是 - 我没有使用任何第三方库(所以没有人可以责怪)

任何形式的帮助将不胜感激

谢谢

最佳答案

您需要在 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了解更多信息。

关于javascript - Node.js 和 https 证书错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com