我试图从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);
});
});
对于无法验证nodejs中的第一个证书,需要拒绝未经授权的证书
request({method: "GET",
"rejectUnauthorized": false,
"url": url,
"headers" : {"Content-Type": "application/json",
function(err,data,body) {
}).pipe(
fs.createWriteStream('file.html'));
这实际上为我解决了这个问题,从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
});
Axios Request:此问题的根本原因是,您的代码无法处理证书管理。要解决此问题,请添加以下代码。
import * as https from "https";
...
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
//现在将httpagent传递给axios请求。像下面。
const { data } = await axios.get(url, { httpsAgent });
我们已经提供了有效的根。pem和Intermediate。返回请求对象的agentOptions属性中的pem证书
ex:
agentOptions: {
ca: [
fs.readFileSync("./ROOT.pem"),
fs.readFileSync("./Intermediate.pem"),
],
},
欲了解更多信息:https://stackoverflow.com/a/72582263/4652706