后端将token发送至前端
目录
后端将token发送至前端
1.在后端登录接口中,如果密码验证成功,则使用jwt模块生成token
const token = jwt.sign(payload, secretOrKey, { expiresIn: '12h' });
2.将token响应给客户端
ctx.body = token;
3.客户端在登录页面中,通过then获取token,再将token设置到local Storage里
const token = res.data.token
localStorage.setItem("userToken",token);
4.每当要发送请求时,就可以通过localStorage来读取token,放在对服务器的请求中,使得服务器能够验证并返回用户数据(路由守卫皆可)
//路由守卫,判断是否登录
router.beforeEach((to, from, next) => {
var isLogin = localStorage.userToken ? true : false
console.log(isLogin);
if (to.path == '/login' || to.path == '/register') {
next()
} else {
if (isLogin) {
next()
} else {
next('/login');
Message.error('请重新登录')
}
}
})