我正在尝试使用 vue-axios 通过 https 进行发布请求。
但是,由于我使用的是我创建的自签名证书,因此出现以下错误:
net::ERR_CERT_AUTHORITY_INVALID
经过搜索,我发现大多数人通过执行以下操作来解决此问题
const instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
instance.get('https://something.com/foo');
// At request level
const agent = new https.Agent({
rejectUnauthorized: false
});
axios.get('https://something.com/foo', { httpsAgent: agent });
我尝试了这两种选择,但都没有成功。
我为 https.Agent 使用了 npm https 模块。
有谁知道如何解决这个问题?还是我应该从 axios 更改为其他模块?
编辑:
我目前正在运行的代码段出现错误:
const axiosInstance = axios.create({
baseURL: 'https://localhost:5000',
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
});
axiosInstance.post('/user', LoginRequest,
{ headers: { 'Content-Type': 'application/json' } })
.then(response => this.assignLogin(response.data));
尝试更改为名为 needle 的模块并使用 https 但出现相同的错误:
针:
const headers = { 'Content-Type': 'application/json' };
const options = {
method: 'POST',
headers: headers,
rejectUnauthorized: false,
requestCert: true,
agent: false,
strictSSL: false,
}
needle.post('https://localhost:5000/user', LoginRequest, options).on('end', function() { })
HTTPS:
const options = {
hostname: 'localhost',
port: 5000,
path: '/user',
strictSSL: false,
rejectUnauthorized: false,
secureProtocol: 'TLSv1_method',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
this.assignLogin(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(LoginRequest);
req.end();
最佳答案
既然您提到您正在“使用您创建的自签名证书”,我猜您正在使用它进行本地开发测试。在 Chrome 中进行本地测试时,我遇到了类似的问题。
由于此错误消息 (net::ERR_CERT_AUTHORITY_INVALID
) 是 Chrome 使用“不安全”证书阻止 URL 的一种方式,因此您需要通过 Chrome 解决此问题,告诉它您信任该证书。
我使用的解决方案是旧的 thisisunsafe
. (仅当您真的信任证书时才使用此解决方案,即,这是您自己的证书):
解决方案 :只需在 Chrome 中打开一个标签,尝试使用您的服务器地址打开一个 URL(在您的情况下为 https://localhost:5000/
)。 Chrome 将显示一条警告消息,因此您可以单击窗口中的任意位置,然后键入 thisisunsafe
. Chrome 现在将允许访问此证书。当您再次重新加载客户端并尝试请求服务器时,它将起作用。
关于vue.js - 使用 axios 获取 ERR_CERT_AUTHORITY_INVALID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381447/