在vue中,可以用sessionStorage或localStorage来存储token,也可以用vuex来存储(但要考虑页面刷新数据消失问题,可以在vuex用Storage),下面介绍用localStorage来存储token
① login.vue组件中登录成功后存储token
login() {
this.$axios.post(" **** ", {
username: this.username,
password: this.$md5(this.password),
}).then((res) => {
if (res.data.code == 200) {
var token = res.data.token;
window.localStorage.setItem("token", token);
this.$router.push({ path: "/index" });
}
});
},
② main.js中设置全局请求头和响应回来的判断
//设置axios请求头加入token
Axios.interceptors.request.use(config => {
if (config.push === '/') {
} else {
if (localStorage.getItem('token')) {
//在请求头加入token,名字要和后端接收请求头的token名字一样
config.headers.token=localStorage.getItem('token');
}
}
return config;
},
error => {
return Promise.reject(error);
});
//响应回来token是否过期
Axios.interceptors.response.use(response => {
//和后端token失效返回码约定403
if (response.data.code == 403) {
// 引用elementui message提示框
ElementUI.Message({
message: '身份已失效',
type: 'err'
});
//清除token
localStorage.removeItem('token');
//跳转
router.push({name: 'login'});
} else {
return response
}
},
error => {
return Promise.reject(error);
})
③ 在router中的index设置全局守卫来判断是否存在token,不存在就返回登录页
router.beforeEach((to, from, next) => {
//to到哪儿 from从哪儿离开 next跳转 为空就是放行
if (to.path === '/') {
//如果跳转为登录,就放行
next();
} else {
//取出localStorage判断
let token = localStorage.getItem('token');
if (token == null || token === '') {
console.log('请先登录')
next({name: 'login'});
} else {
next();
}
}});