【发布时间】:2021-02-10 12:38:03
【问题描述】:
我的项目正在使用 vuex、axios、vue-cookies 和 JWT。我有一个名为 api.js 的文件,它被导入到我的主 vue js 中,api.js 代码如下;
import axios from 'axios'
import Vue from 'vue'
import { store } from "@/store";
export default axios.create({
baseURL: store.state.endpoints.baseUrl,
headers: {
Authorization: `JWT ${Vue.$cookies.get('token')}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
当我通过我的登录页面登录时,一切都显示成功。在检查器中,cookie 'token' 值使用新令牌正确更新,Vuex 更新以显示用户已通过身份验证,路由器将我重定向到主页。 进入主页后,如果我尝试导航到进行任何需要身份验证的调用的页面,则在标头中它会传递“JWT null”而不是 cookie 中的令牌并失败,并且我最终会进入成功记录的永久循环在但不能去任何地方。
如果我登录并在执行任何其他操作之前刷新页面,一切都会按预期工作,并且 JWT 不再为空。 似乎这个问题顶部的 api.js 代码在每次调用它时都没有正确地从 cookie 中提取令牌,而只是在页面刷新时,这是被缓存了,还是我需要在登录后以某种方式重新加载这个导入?
作为参考,我的登录页面中的一段代码,用于显示登录后数据是如何更新的;
api.post(this.$store.state.endpoints.obtainJWT, payload)
.then((response) => {
console.log("Token - "+response.data.token);
console.log("Profile - "+response.data.user);
this.$cookies.set('token', response.data.token);
this.$store.commit("setAuthUser",
{authUser: response.data, isAuthenticated: true})
})
.then(() => this.$router.push({path: '/'}))
.catch((error) => {
console.log("Error!");
console.log(error);
console.debug(error);
console.dir(error);
})
如果在刷新页面之前访问,则包含“JWT null”的 api 调用示例;
import api from "../api.js";
...
api.get("/data_full/" + id)
.then((response) => {
this.title = response.data.title;
})
在我的项目 main.js 中,api.js 导入;
...
import api from './api.js'
...
Vue.$http = api;
【问题讨论】:
标签: javascript vue.js