【发布时间】: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