0

I met a weird problem, when I set up main.js and run the server, it shows me this error enter image description here

and here is my code in 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')

I set a console.log to track the error, the '1111' shows but 'aaa' never shows, so I can only know the error occurs in the line app.use(axios), that's so confusing, did anyone ever met this problem? How to solve it?

Mr B
  • 23
  • 3

1 Answers1

-1

Here you have 2 options:

  • If you're using Vue3, import it in your Vue, like you did, but as written in this awnser, i think you should do something more like that:
import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App)
app.use(VueAxios, axios) // 
app.mount('#app')
  • You wanna use only axios and don't get bothered by it, then you don't have to use VueAxios or make something like app.use(axios) in your main.js, and then make a httpRequestsService file which will handle all the axios part.

For example, here is mine:

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))
    },
}
Kharente Deuh
  • 206
  • 2
  • 6
  • Thank you for the answer, actually I solved my problem by adding the axios along with router like this `app.use(router, axios)`, idk why this could work but that do fixed the error – Mr B Jun 17 '21 at 01:38