【问题标题】:Nuxt.js - accessing store state in axios pluginNuxt.js - 在 axios 插件中访问存储状态
【发布时间】:2021-07-24 00:09:48
【问题描述】:

我在商店中有一个令牌,但我无法在我的 axios 插件中访问它。我以前只使用 Vue 时只是简单地导入商店,真的很难理解如何在 Nuxt.js 中做到这一点

我需要从我的商店访问一个令牌值,并在下面的“授权”属性中使用它。

这是我当前的代码;

// /plugins/axios.js
import axios from 'axios'
import { state } from '../store'

export default () => {
    const api = axios.create({
        baseURL: process.env.BASE_URL,
        headers: {
            Authorization: `Bearer` + xxxx ACCESS STORE STATE HERE xxxx,
        },
    })

    return api
}
// nuxt.config.js
...
{
  plugins: ['~/plugins/persistedState.client.js', '~/plugins/axios'],
}
...
// store/index.js
export const state = () => ({
    token: null,
    user: null,
    isUserLoggedIn: false,
})

由于状态是作为我的 store/index.js 中的函数返回的,我无法让它工作,显然不是解决方案!

我尝试过的

查看文档和旧帖子,看起来我需要将 { store } 作为参数传递,但我收到错误 Cannot destructure property 'store' of 'undefined' as it is undefined.

例如...

export default ({ store }) => {
    const api = axios.create({
        baseURL: process.env.BASE_URL,
        headers: {
            Authorization: `Bearer` + store.state.token,
        },
    })

    return api
}

我也尝试在商店本身中设置 Authorization 标头作为替代方案,但这在发布到我的服务器时没有任何效果,没有提供授权标头。

// store/index.js
...
export const mutations = {
    setToken(state, token) {
        state.token = token
        state.isUserLoggedIn = !!token
        this.$axios.setHeader('Authorization', '123')
    },

对此有点茫然,非常感谢任何帮助。

【问题讨论】:

  • 您能告诉您您的nuxtaxios 版本吗?

标签: javascript vue.js axios nuxt.js


【解决方案1】:

插件函数应该是纯函数,并且不应使用=>(粗箭头)重新分配$this 的值。

您可以利用当前的$axios 实例并在发出请求时设置标头:

// plugins/axios.js
export default function ({ $axios, store }) {
  $axios.onRequest(config => {
    const { token } = store.state

    if (token) {
      config.headers.common.Authorization = `Bearer ${token}`
    }

  })
}

请注意,$axios 是由@nuxtjs/axios 提供的包,如果您自己手动注册了axiosthis.$axios 将不同于this.axios

【讨论】:

  • 您好,感谢您的回复。使用上面的代码我得到错误Cannot destructure property '$axios' of 'undefined' as it is undefined. 有什么想法吗?
  • 已解决 - 因为仍在将上面的 axios.js 文件导入另一个模块。
猜你喜欢
  • 1970-01-01
  • 2020-02-08
  • 2017-12-05
  • 2019-08-25
  • 2018-11-06
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
相关资源
最近更新 更多