1.登陆成功之后,将token存储在localStorage
localStorage.setItem('token',res.data.token)
2.请求数据需要用到token的页面:
let token = localStorage.getItem('token')
axios.get('url',{
headers:{Authorization:token},
params:{
pagesize:10
}
}).then(res=>{
console.log(res)
})
3.但是每次请求都要发送token,岂不是太麻烦了,这里要用到拦截器:
在发送请求的api文件中可以这样写:
axios.interceptors.request.use(function(config){
let token = localStorage.getItem('token')
if(token){
config.headers.Authorization = token
}
return config
},function(error){
return Promise.reject(error)
})
在发送请求之前,请求头会加上token.
4.导航守卫:
main.js中:
router.beforeEach((to,from,next)=>{
let token = localStorage.getItem('token')
if(!token&&to.path!=='/login'){//to.path!='login'不写会造成死循环
return next({path:'/login'})
}
if(token&&to.path=='/login')return next({path:'/home'})
next()//一定要加next
})
注意:加了导航守卫,存储token一定要在路由跳转之前
5.退出登录:
点击之后:
localStorage.removeItem('token')
this.$router.push('/login')