我是Vue的新手,所以我不知道如何实现以下目标:
我想要一个Axios响应,所以我可以将响应令牌与本地存储的令牌匹配,因为我发现如果我修改本地存储中的令牌值,用户仍然可以从任何安全路由导航。
还有其他方法来保护这个吗?
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)){
const authUser = localStorage.getItem('authUser')
console.log(authUser);
var session='here i want axios response value'
if (!authUser===session){
console.log('here log');
next({ path: '/', })
} else {
console.log('else redirect');
next()
}
} else {
console.log('bhar else redirect');
next()
}
});
这是我的login.vue成功loginpost方法:
loginPost(){
var _this = this
var vm = this.hasErrors
var _vm = this.errorMessage
var log = {
companyname: this.loginData.companyname,
username: this.loginData.both,
password: this.loginData.password,
}
this.$http.post('http://localhost:3000/api/users/login', log)
.then(function (response) {
if(response.status=== 200){
this.$store.commit('authUser', response.data.id)
localStorage.setItem('authUser', response.data.id)
_this.$router.push('/authuser');
}else{
console.log('unknow');
}
})
.catch(function (error) {
var errors = error.response;
if(errors.statusText === 'Unprocessable Entity'){
if(errors.data){
if(error.response.data.error.details.messages.username){
vm.both = true
_vm.both = error.response.data.error.details.messages.username[0]
}
}
}
});
答案 0 :(得分:-1)
我不确定你要做什么,但我想我明白了。你从后端获取令牌,所以用户已经过身份验证。你必须知道在令牌旁边你也得到了用户。所以用户的ID。当用户成功登录然后在登录时,您可以执行以下操作:
this.$store.commit('authUser', response.data.user.id)