在 NuxtJS 中使用 Authenticated 全局配置 Axios - VueJS

Config Axios globally with Authenticated in NuxtJS - VueJS

我找到了在 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

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

// ~/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 header,需要在拦截器的开头加上if。

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

const AuthenticationStore = () => { 

您应该这样导出实例:

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

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