axios 请求报错 Unable to verify the first certificate

2,807 阅读1分钟

问题

使用Axios请求接口,报错如下

AxiosError: unable to verify the first certificate\
at TLSSocket.onConnectSecure (_tls_wrap.js:1514:34)\
at TLSSocket.emit (events.js:400:28)\
at TLSSocket.emit (domain.js:470:12)\
at TLSSocket._finishInit (_tls_wrap.js:936:8)\
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:708:12)\
at TLSWrap.callbackTrampoline (internal/async_hooks.js:131:17) {\
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',

问题原因

在使用浏览器访问时,客户端、服务器在握手阶段完成验证。当我们在node中使用axios请求时,客户端没法确认服务端的TLS证书

解决方案

取消TLS验证报错

// DO NOT DO THIS IF SHARING PRIVATE DATA WITH SERVICE
const httpsAgent = new https.Agent({ rejectUnauthorized: false });

代码示例
```js
const https = require("https");
// 在 axios 请求时,选择性忽略 SSL
const agent = new https.Agent({
  rejectUnauthorized: false
});
axios.get(url, {
    httpsAgent: agent
})

参考链接

stackoverflow.com/questions/5…