我试图从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);
});
});
这为我工作=>添加代理和'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;
});
};
您是否使用axios发送请求并得到此错误?
如果是这样,就把这看作是错误
无法验证第一个证书可能来自axios,与服务器无关。为了解决这个问题,您必须配置axios(或其他请求生成应用程序)以允许未经授权的请求。添加https。代理在请求的配置中设置rejectUnauthorized: false:
import axios from "axios"
import https from "https"
const getCities = async () => {
try {
const result = await axios.get("https://your-site/api/v1/get-cities", {
httpsAgent: new https.Agent({
rejectUnauthorized: false // set to false
})
})
console.log(result.data)
} catch(err) {
console.log(err?.message||err)
}
}
如果您正在使用自定义axios实例,则:
import axios from "axios"
import https from "https"
export const request = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Authorization: cookies.YOUR_ACCESS_TOKEN,
},
httpsAgent: new https.Agent({
rejectUnauthorized: false //set to false
})
})