路由守卫
//index.js
router.beforeEach((to, from, next) => { // to表示前端请求去哪个路径,from表示从哪个网页过来,next表示引导到何处
if(to.path === '/login') return next() // next()放行
const token = localStorage.getItem('token') // 从localStorage获取token
if(!token || token === '') return next('/login') // 若无token,引导到登陆页面
next()
})
存储token
// token="eyJhbGciOiJIUzI1NiJ9.eyJpbWFnZSI6ImFkbWluLmpwZyIsIm5hbWUiOiJhZG1pbiIsInBlcm1pc3Npb24iOiJyb290IiwiaWQiOjEwMDAwMCwiZW1haWwiOiIxMzUxQHFxLmNvbSIsImV4cCI6MTcwODE1ODA4MH0=.EKs0ywuf6KQJEykiFpA25KIeG4HpcC3VkA7dCKgpjoM"
localStorage.setItem("token", token);
路由跳转
this.$router.push("/path");
解析JWT
paeseToken(){
const token = localStorage.getItem("token"); // 从localStorage获取JWT
const payload = token.split('.')[1]; // 取JWT的第二部分payload
const decodedJson = atob(payload); // atob进行base64解码
return JSON.parse(decodedJson); // JSON解析字符串,得到对象,JSON.stringify()封装字符串
}
前端请求JWT
axios.post("http://localhost:8080/login", this.object).then((response) => { // POST请求,参数1:URL,参数2:登录账号和密码的对象
if(response.data.code == 1){ // 响应成功
var token = response.data.data;
localStorage.setItem("token", token); // localStorage存储token
this.$router.push("/home"); // 自动跳转
} else {
this.notice(token); // 错误提示
}
})
前端携带JWT
// axios.post(url, dataObject, config)
axios.post("http://localhost:8080/emp", this.object, {
headers: { 'token': localStorage.getItem('token') }
}).then((result) => { });