var options = {
key: fs.readFileSync("./cert/server.key"),
cert: fs.readFileSync("./cert/server.cert")
};
app.get("/", (req, res) => {
console.log("test 1");
res.send("Hello World111!");
});
var server = https.createServer(options, app);
server.listen(port, function() {
console.log("Express server listening on port " + server.address().port);
});
以上是使用自签名证书的代码。
当我尝试从不同的 NodeJS 应用程序访问 API 时,如下所示。
try {
const agent = new https.Agent({
requestCert: true,
rejectUnauthorized: false,
ca: fs.readFileSync("./cert/server.pem")
});
let response = await axios.get(url, { httpsAgent: agent });
if (response.status == 200) {
return await response.data;
}
} catch (error) {
console.log(error, "Error in getAuth Token");
throw new Error("Network Error, Error receiving token");
}
我收到以下错误:
Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1055:34)
at TLSSocket.emit (events.js:198:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8)
code: 'DEPTH_ZERO_SELF_SIGNED_CERT',
config:
{ url: 'https://localhost/',
method: 'get',
headers:
我不想将rejectUnauthorized 设置为true。或设置任何 nodejs 参数以拒绝证书。
我希望证书毫无异常(exception)地被接受。提前致谢。
最佳答案
我遇到了同样的错误,我只是将 ca 更改为 cert 并为我工作
const agent = new https.Agent({
requestCert: true,
rejectUnauthorized: false,
cert: fs.readFileSync("./cert/server.pem")
});
关于node.js - Axios 访问自签名证书而不拒绝它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737816/