如何将ssl-root-cas与axios配合使用以解决证书验证错误
解决Axios请求中“unable to verify the first certificate”错误的正确姿势
我来帮你搞定这个SSL证书验证的问题~你遇到的Error: unable to verify the first certificate,本质是Node.js默认的根证书信任列表里没有目标服务器使用的CA证书,所以需要用ssl-root-cas来扩展可信证书,再配合Axios的自定义Agent来生效。
先说说你之前代码的问题:直接修改https.globalAgent.options.ca或者给axios.agent赋值的方式不对,Axios不会直接识别这种全局修改或者直接挂载的agent属性,正确的做法是创建自定义HTTPS Agent并在请求配置中指定。
正确步骤和代码示例
- 先确保安装了依赖:
npm install ssl-root-cas axios
- 编写代码:
// 引入所需模块 const rootCas = require('ssl-root-cas/latest').create(); const https = require('https'); const axios = require('axios'); // (可选)如果目标服务器用的是自签CA证书,把证书文件路径加进来 // rootCas.addFile('./path/to/your-custom-ca.crt'); // 创建自定义HTTPS Agent,传入我们的根证书集合 const customHttpsAgent = new https.Agent({ ca: rootCas }); // 发送请求时,在配置里指定httpsAgent axios.get('https://你的目标接口地址', { httpsAgent: customHttpsAgent }) .then(response => { console.log('请求成功:', response.data); }) .catch(err => { console.error('请求失败:', err); });
让所有Axios请求默认使用这个Agent
如果不想每次请求都写httpsAgent,可以创建一个Axios实例,把Agent配置进去:
const customAxios = axios.create({ httpsAgent: customHttpsAgent }); // 之后用这个实例发的所有请求都会自动使用自定义证书 customAxios.get('https://你的目标接口地址') .then(res => console.log(res.data));
额外提醒
如果你只是测试环境临时用,也可以在Agent里设置rejectUnauthorized: false跳过证书验证,但绝对不要在生产环境这么做,这会带来严重的安全风险:
const insecureAgent = new https.Agent({ rejectUnauthorized: false });
内容的提问来源于stack exchange,提问作者user4893295




