在 node.js 中使用 axios 時,有時需要忽略 SSL 證書,在百度搜半天都搜不到,最后在 axios 的 github issue 中找到了解決辦法。
需要注意本文介紹的是在 node.js 服務端中使用 axios,不是在前端使用,前端由於網絡操作都要經過瀏覽器,瀏覽器自身要做安全上的保障,所以不能忽略證書
首先需要在項目中使用以下命令導入https
和axios
依賴:
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 });