我试图从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://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
});

其他回答

您可以通过如下所示修改请求选项来做到这一点。如果使用自签名证书或缺少中介,将strictSSL设置为false将不会强制请求包验证证书。

var options = {
   host: 'jira.example.com',
   path: '/secure/attachment/206906/update.xlsx',
   strictSSL: false
}

您试图下载的服务器可能配置错误。即使它在您的浏览器中工作,它也可能不包括缓存空客户端验证所需的链中的所有公共证书。

我建议在SSLlabs工具中检查该站点:https://www.ssllabs.com/ssltest/

查找以下错误:

此服务器的证书链不完整。

这:

链问题……不完整

这为我工作=>添加代理和'rejectUnauthorized'设置为false

const https = require('https'); //Add This const bindingGridData = async () => { const url = `your URL-Here`; const request = new Request(url, { method: 'GET', headers: new Headers({ Authorization: `Your Token If Any`, 'Content-Type': 'application/json', }), //Add The Below agent: new https.Agent({ rejectUnauthorized: false, }), }); return await fetch(request) .then((response: any) => { return response.json(); }) .then((response: any) => { console.log('response is', response); return response; }) .catch((err: any) => { console.log('This is Error', err); return; }); };

我们已经提供了有效的根。pem和Intermediate。返回请求对象的agentOptions属性中的pem证书

ex:

   agentOptions: {
        ca: [
            fs.readFileSync("./ROOT.pem"),
            fs.readFileSync("./Intermediate.pem"),
        ],
    },

欲了解更多信息:https://stackoverflow.com/a/72582263/4652706

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

// 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

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