我试图从jira服务器下载一个文件使用URL,但我得到一个错误。 如何在代码中包含证书进行验证?

错误:

Error: unable to verify the first certificate in nodejs

at Error (native)
    at TLSSocket.<anonymous> (_tls_wrap.js:929:36)
   
  at TLSSocket.emit (events.js:104:17)

at TLSSocket._finishInit (_tls_wrap.js:460:8)

我的Nodejs代码:

var https = require("https");
var fs = require('fs');
var options = {
    host: 'jira.example.com',
    path: '/secure/attachment/206906/update.xlsx'
};

https.get(options, function (http_res) {
    
    var data = "";

  
    http_res.on("data", function (chunk) {
       
        data += chunk;
    });

   
    http_res.on("end", function () {
      
        var file = fs.createWriteStream("file.xlsx");
        data.pipe(file);
      
    });
});

当前回答

这对我很有效

做下面的事情

如果你没有这些包https和axios

您可以通过 NPM安装——保存axios HTTPS

import axios from 'axios';
import https from 'https';
const httpsAgent = new https.Agent({
    rejectUnauthorized: false,
})

axios.defaults.httpsAgent = httpsAgent

这样做你就会得到你的回应。

其他回答

我遇到过非常罕见的情况,但希望它能帮助到某人:做一个代理服务,代理请求到另一个服务。而且每个请求的错误都是“无法验证第一个证书”,即使我添加了所有预期的证书。

原因很简单-我不小心重新发送也“主机”头。 只是要确保你没有显式地发送“host”头。

您可以全局禁用证书检查-无论您使用哪个包来发出请求-就像这样:

// Disable certificate errors globally
// (ES6 imports (eg typescript))
//
import * as https from 'https'
https.globalAgent.options.rejectUnauthorized = false

Or

// Disable certificate errors globally
// (vanilla nodejs)
//
require('https').globalAgent.options.rejectUnauthorized = false

当然,您不应该这样做——但这对于调试和/或非常基本的脚本编写非常方便,您完全不需要关心证书是否正确验证。

@sch提供的答案对我帮助很大。我还想补充一些东西。 在开发环境中工作时,您的SSL证书是由您自己的一个自签名证书颁发的(因此不存在中间证书),NODE_EXTRA_CA_CERTS环境变量需要引用这个自签名证书。自签名证书需保存为PEM格式。导出证书后,我做了以下操作:

set NODE_EXTRA_CA_CERTS=C:\rootCert.pem

(值得注意的是,我在Windows上运行node,到PEM的路径没有引用)

使用命令行中的{{node}},我能够确认是否已经解决了这个问题,通过调用:

https.get("https://my.dev-domain.local")

这实际上为我解决了这个问题,从https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

GoDaddy SSL CCertificate

我在尝试使用GoDaddy证书连接到我们的后端API服务器时遇到过这种情况,下面是我用来解决问题的代码。

var rootCas = require('ssl-root-cas/latest').create();

rootCas
  .addFile(path.join(__dirname, '../config/ssl/gd_bundle-g2-g1.crt'))
  ;

// will work with all https requests will all libraries (i.e. request.js)
require('https').globalAgent.options.ca = rootCas;

PS:

使用捆绑的证书,不要忘记安装npm install ssl-root-cas库