[英]Vue load page after save to store token auth
我创建文件JS以从数据库获取令牌并将其保存在会话sotorage中,然后将此文件导入到Vue中的app.js:
import Auth from './auth/auth';
new Vue({
el: "#app_resource",
router,
store,
beforeMount() {
window.auth = new Auth();
},
render: h => h(App)
});
文件auth.js
import axios from 'axios';
class Auth {
constructor() {
this.getToken();
let token = window.sessionStorage.getItem('token');
if (token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
}
getToken(){
let options = {
method: "post",
url: "/getapitoken",
headers: {
'Accept': 'application/json'
}
};
axios(options)
.then(response => {
let token = response.data.token
if (token) {
this.issetToken(token);
}
})
.catch(({ response }) => {
console.warn(response);
});
}
issetToken(token){
if (window.sessionStorage.getItem('token') === null) {
window.sessionStorage.setItem('token', token);
} else {
window.sessionStorage.removeItem('token');
window.sessionStorage.setItem('token', token);
}
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
}
export default Auth;
会话存储中的令牌保存正确,但我有一个问题,因为我在登录后重定向到启动页面,在开始页面上从数据库获取数据,我需要令牌来获取此数据。 但是Vue返回错误401(未经授权)(如Vue看不到令牌)。 我必须刷新页面,现在我可以从数据库中获取数据。
登录后如何在没有刷新页面的情况下获取日期?
我相信,问题在于,当您在其他地方提出请求时,您将获得令牌。
以下是我认为正在发生的一系列事件。
现在当你刷新页面时......
如果是这种情况,您需要做的就是推迟任何api活动,直到您拥有令牌。 当然,这可能不是直截了当的,因为您需要知道令牌是否已设置,并链接请求还是有某种方式。
您可以尝试暂停重定向,直到您的getToken成功(虽然我不知道您是如何处理的)通过让函数返回一个promise
getToken(){
let options = {
method: "post",
url: "/getapitoken",
headers: {
'Accept': 'application/json'
}
};
return axios(options)
.then(response => {
let token = response.data.token
if (token) {
this.issetToken(token);
return token;
}
})
.catch(({ response }) => {
console.warn(response);
});
}
然后你可以使用像window.auth.getToken().then(()=>doMyRedirect())
那样的东西window.auth.getToken().then(()=>doMyRedirect())
我过去处理这些情况的方法是使用Vuex,并在Vuex存储中保存状态信息,因此任何其他函数都可以检查当前是否正在提取令牌,因此没有其他请求同时进行,但是仍需要一些逻辑才能使请求发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.