这是由于请求协议(http/https)与 Node.js 模块支持的协议不一致导致的。解决方法是在发送请求时,添加 https.Agent 选项,让 Node.js 模块使用正确的协议处理请求。
代码示例如下:
const https = require('https');
const axios = require('axios');
const agent = new https.Agent({
rejectUnauthorized: false
})
axios.get('https://example.com', {
httpsAgent: agent
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
其中,https.Agent 中的 rejectUnauthorized 选项表示是否验证服务器证书,默认为 true,即验证证书。如果服务器证书无效,可以尝试将其设为 false。