Nuxt 3 中的 Axios 插件

问题描述 投票:0回答:1

我尝试使用插件在 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 实例没有以某种方式创建。

我做错了什么?

axios nuxtjs3
1个回答
3
投票

使用了错误的语法 这是正确的:

baseURL: domain

现在可以了

© www.soinside.com 2019 - 2024. All rights reserved.