我尝试使用插件在 nuxt 3 中配置 Axios。 当我研究文档时,不再需要
nuxt.config
中的插件要求,我立即在我的插件文件夹中创建了该文件:
export default defineNuxtPlugin(nuxtApp => {
const domain = 'http://localhost:3000/v1/'
const username = "abcdef"
const password = "123456"
const token = `${username}:${password}`
const encodedToken = Buffer.from(token).toString('base64')
let publicApi = nuxtApp.$axios.create({
baseUrl: domain,
headers: {
common: {
Authorization: `Basic ${encodedToken}`
}
}
})
return {
provide: {
publicApi: publicApi
}
}
})
然后我尝试在组件中调用新注入的变量:
this.$publicApi.$get('some_endpoint')
它成功地通过 axios 触发了一个请求,但是之前配置的
baseUrl
和 headers
是空的,所以看来我的 axios 实例没有以某种方式创建。
我做错了什么?
使用了错误的语法 这是正确的:
baseURL: domain
现在可以了