首页 > 解决方案 > Nuxt.js/Axios 自签名证书错误

问题描述

我在GET从 http 到 https 发出本地请求时遇到问题。

情况:我使用一个叫Local( https://localwp.com/ )的工具来快速生成一个本地的WordPress开发环境。它的本地地址是https://backend.local(通过主机文件)。我还有一个 Nuxt.js 应用程序在http://localhost:3000上运行。

使用 axios,我尝试向GETWordPress REST api 发出请求,但出现以下错误:

NuxtServerError

self signed certificate 

如果我尝试该fetch方法,我会得到以下响应:

FetchError
request to https://backend.local/wp-json/wp/v2/posts failed, reason: self signed certificate

它仅在我GET向非本地 URL 发出请求时才有效。

但是经过几个小时的谷歌搜索并尝试了所有解决方案,没有任何效果,我现在有点沮丧:)

我的设置是:MacBook Pro 2019 Catalina 10.15.4,Chrome 83.0.4103.61

我希望有人能给我一个答案:)

谢谢!

标签: vue.jsaxiosssl-certificatenuxt.jsself-signed

解决方案


我按照这些步骤解决了这个问题:

1. 创建一个plugins文件夹,如果它不存在。在plugins文件夹中,使用以下内容创建axios.js文件:

import https from 'https';

export default function ({ $axios }) {
    $axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false });
}

2. 在nuxt.config.js文件中,找到该plugins部分,然后添加以下内容:

// Other configurations here
plugins: [
    // Other plugins here
    '@/plugins/axios',
],
// Rest of the file

推荐阅读