这里有 2 个选项:
- 如果您使用的是 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))
},
}