(vue) Uncaught InternalError: too much recursion: failed to use axios

时间:2021-06-16 09:44:20

标签: vue.js axios

我遇到了一个奇怪的问题,当我设置 main.js 并运行服务器时,它显示了这个错误 enter image description here

这是我在 main.js 中的代码,

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus';
import axios from 'axios'
import 'element-plus/lib/theme-chalk/index.css';

axios.defaults.baseURL = 'http://localhost:8000'

const app = createApp(App)
app.use(store)
app.use(router)
app.use(ElementPlus)
console.log('1111')
app.use(axios)
console.log('aaa')
app.mount('#app')

我设置了一个console.log来跟踪错误,'1111'显示但'aaa'从不显示,所以我只能知道错误发生在app.use(axios)行中,这太令人困惑了,有没有人做过遇到这个问题了吗?如何解决?

1 个答案:

答案 0 :(得分:0)

这里有两个选项:

  • 如果您使用的是 Vue3,请像您一样将其导入您的 Vue,但正如 this awnser 中所写,我认为您应该做更多类似的事情:
import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App)
app.use(VueAxios, axios) // ?
app.mount('#app')
  • 你只想使用 axios 而不会被它打扰,那么你不必使用 VueAxios 或在你的 main.js 中创建类似 app.use(axios) 的东西,然后创建一个 httpRequestsService 文件,它将处理所有 axios 部分。

例如,这是我的:

import axios from "axios";

axios.defaults.baseURL = process.env.API_BASE_URL
axios.interceptors.response.use(res => res, err => {
    // some code if you wanna handle specific errors
    throw err;
  }
);

const getHeader = (method, endpoint, header, body) => {
    const publicEndpoints = [
        {
            method: 'POST',
            endpoint: '/auth/local'
        }
    ]

    const publicEndpoint = publicEndpoints.find(e => e.method === method && e.endpoint === endpoint)
    if (!publicEndpoint) {
        header.Authorization = localStorage.getItem("jwt")
    }

    return body ? { headers: header, data: body } : { headers: header }
}

export default {
    get(endpoint, header = {}) {
        return axios.get(endpoint, getHeader('GET', endpoint, header))
    },
    post(endpoint, body = {}, header = {}) {
        console.log(body)
        return axios.post(endpoint, body, getHeader('POST', endpoint, header))
    },
    put(endpoint, body = {}, header = {}) {
        return axios.put(endpoint, body, getHeader('PUT', endpoint, header))
    },
    delete(endpoint, body = {}, header = {}) {
        return axios.delete(endpoint, getHeader('DELETE', endpoint, header, body))
    },
}