节点 'DEPTH_ZERO_SELF_SIGNED_CERT'

NodeJS 'DEPTH_ZERO_SELF_SIGNED_CERT'

当我尝试使用我正在编写的 node.js 客户端连接到网络服务器时出现上述错误。

但是当我尝试连接到服务器时出现错误。

'DEPTH_ZERO_SELF_SIGNED_CERT'

这是发送请求的代码。关闭证书检查不是一个有效的选项。我需要确保连接安全。

var options = 
    {
        hostname: baseUri,
        port: 443,
        path: 'oauth',
        method: 'POST',
        requestCert: true,
        ca:fs.readFileSync('Comodo_PositiveSSL_bundle.crt'),
        rejectUnauthorized: true,
        headers: {
            //'User-Agent': USER_AGENT,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': data.length
        }
    };

    var req = http.request(options, (res) => {
      console.log('statusCode: ', res.statusCode);
      console.log('headers: ', res.headers);

      res.on('data', (d) => {
        process.stdout.write(d);
      });
    });

    req.write(data)
    req.end();

    req.on('error', (e) => {
      console.error(e);
    });

如果有人能告诉我如何设置正确的证书才不会产生错误?


证书包的图片。如您所见,捆绑包仅包含验证服务器自身提供的证书所需的根证书。

问题已通过以下代码解决。我添加了 options.agent = http.Agent(options); 并解决了问题。

因此,对于所有尝试向安全服务器进行身份验证并收到上述错误的人来说,这可能是您的解决方案。下面我添加了上面的编辑代码。

var options = 
        {
            hostname: baseUri,
            port: 443,
            path: 'oauth',
            method: 'POST',
            requestCert: true,
            headers: {
                //'User-Agent': USER_AGENT,
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': data.length
            }
        };
        options.agent = http.Agent(options);

        var req = http.request(options, (res) => {
          console.log('statusCode: ', res.statusCode);
          console.log('headers: ', res.headers);

          res.on('data', (d) => {
            process.stdout.write(d);
          });
        });

        req.write(data)
        req.end();

        req.on('error', (e) => {
          console.error(e);
        });

npm 配置设置 strict-ssl false 适用于 npm 管理的项目

此解决方案与发布的问题无关,但错误代码为 DEPTH_ZERO_SELF_SIGNED_CERT。

下面的代码抛出相同的错误代码

const https = require('https');

https.get('https://10.20.30.40:1234/v1/objects/storages', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

要解决这个问题,我们必须在 https.get() 中应用 process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"。请查看以下行中的问题修复代码。

const https = require('https');

https.get('https://10.20.30.40:1234/v1/objects/storages',
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0", (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});