axios忽略SSL证书,不校验https证书

时间:2024-03-01 20:24:57

在 node.js 中使用 axios 时,有时需要忽略 SSL 证书,在百度搜半天都搜不到,最后在 axios 的 github issue 中找到了解决办法。

需要注意本文介绍的是在 node.js 服务端中使用 axios,不是在前端使用,前端由于网络操作都要经过浏览器,浏览器自身要做安全上的保障,所以不能忽略证书

首先需要在项目中使用以下命令导入httpsaxios依赖:

npm i https
npm i axios

然后可以根据不同的需求编写代码:

const https = require(\'https\');
const axios = require(\'axios\');

// 创建忽略 SSL 的 axios 实例
const ignoreSSL = axios.create({
  httpsAgent: new https.Agent({  
    rejectUnauthorized: false
  })
});
ignoreSSL.get(\'https://something.com/foo\');

// 在 axios 请求时,选择性忽略 SSL
const agent = new https.Agent({  
  rejectUnauthorized: false
});
axios.get(\'https://something.com/foo\', { httpsAgent: agent });