【问题标题】:Config Axios globally with Authenticated in NuxtJS - VueJS在 NuxtJS 中使用 Authenticated 全局配置 Axios - VueJS
【发布时间】:2018-06-30 19:02:18
【问题描述】:

我想办法在 NuxtJS - VueJS 中使用 Authenticated 全局配置 Axios(我主要使用 NUXTJS)。

我只需要:如果用户登录并在 $store 中有令牌,axios 将获得这个令牌。如果用户是匿名用户,axios 不会得到这个令牌

~/plugins/axios

import axios from 'axios'
import AuthenticationStore from '~/store'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/',
  'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})

api.interceptors.request.use(function (config) {
  config.headers = {
    'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

export default api

~/store/index.js

const AuthenticationStore = () => {
  return new Vuex.Store({
    state: {
      token: null
    },
    mutations: {
      SET_TOKEN: function (state, token) {
        state.token = token
        instance.defaults.headers = { Authorization: 'Bearer ' + token }
      }
    },
    actions: {
      ....
    }
  })
}

export default AuthenticationStore

错误:[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined

【问题讨论】:

  • 您是否尝试将状态导出为类似以下的函数:export const state = () => ({ // go here })
  • 我试过了,就像你在~/store/index.js 中所说的那样。请看我上面的代码!
  • 好吧,我只是想知道您是否尝试过here 所示的模块方法,但显然它更像是经典方法。然后,我可以说使用像this.$state.token 这样的状态可能会有所帮助。
  • @vahdet 谢谢。我试试看

标签: vue.js vuejs2 axios vuex nuxt.js


【解决方案1】:

我建议改用拦截器,它更灵活,并且在不创建请求时获取令牌。尝试类似的方法来避免未设置令牌的问题。

// ~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'

var api = axios.create({
  baseURL: 'http://localhost:8000/api/v1/',
  'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
 api.interceptors.request.use(function (config) {
  config.headers = {
    'Authorization': AuthenticationStore.state.token ? 'Bearer ' + AuthenticationStore.state.token : ''
  }
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})
export default api

如果你需要没有auth头,你需要在拦截器的乞求时添加if。

您的商店有问题: 当您应该导出商店实例时,您正在导出功能, 所以这是错误的:

const AuthenticationStore = () => { 

你应该这样导出实例:

const AuthenticationStore = new Vuex.Store({ ...

请访问https://vuex.vuejs.org/guide/以获得更好的了解。你不完全理解它也不错! JS 中的模块/实例/导出并不是很容易完全理解。只是尝试更多地学习它。祝你好运。

【讨论】:

  • 抱歉,store/index.js 中的代码我弄错了。请查看我上面的代码。我有一些关于将商店导入 axios.js 文件的问题。
  • 你到底有什么问题?
  • 我的错误是[nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined
  • 当我 console.log(AuthenticationStore) 时,它呈现:AuthenticationStore() { return new __WEBPACK_IMPORTED_MODULE_7_vuex__["default"].Store({ state: { authUser: null, userInfo: null, token: null },
  • 更新了我的答案。希望对你有帮助
猜你喜欢
  • 1970-01-01
  • 2020-09-12
  • 2017-11-28
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 2021-07-02
  • 2022-06-12
  • 1970-01-01
相关资源
最近更新 更多