Relative will call security token is the use of a combination of forms of data transmission, is produced by the background, and transferred to the front desk, reception can be saved, at the front desk can carry token each time you send the request, the background can be validated for token, authenticated by can request to make the right response to the data, or sleep of return an error code

Token has its own expiration time, and is implemented in the background, the front desk nothing-thinking so much, the specific front desk steps are divided into three parts

1. During login, the background will give a token code, and the foreground will store it in cookie, LocalStroage or LocalSession

Please note the need to concatenate string ‘Bearer ‘+ in front of tooken, fixed format

login(){
            axios.post('/user/login',this.user).then((res)=>{
                localStorage.setItem('token'."Bearer "+res.data.res.token)
            })
        }Copy the code

2. Set the guard navigation on the Router

Check whether the token exists. If so, the token will be carried to the next cluster of operations. If not, return to login

router.beforeEach((to,from,next)=>{
    if(to.matched.some((route)=>route.meta.Auth)){
        if(localStorage.getItem('token')){
            next()
        }else{
             next({
                path:'/login',
                query:{
                    returnURL:to.path
                }
            })
        }
       
    }else{
         next()
    }
   
})Copy the code

3. Carry Tooken in axios’ request interceptor for requests

axios.interceptors.request.use(config=>{
    const token=localStorage.getItem('token') / /if(token){ token? config.headers.Authorization=token:null; / /}return config
});Copy the code

Each request carries a token. If the token is not verified in the background, it is a problem in the background

Set the token reply interceptor to handle the incorrect receipt code

axios.interceptors.response.use(res=>{
    if(res.data.res_code=== 401){
        router.replace('/login');
        localStorage.removeItem('token')}return res
})Copy the code

This according to the background receipt code to change on the line