the authentication token vue cli

1. Set the front end of route jumps

router.beforeEach ((to, from , Next) => {
 IF (to.matched.some (route => route.meta.auth)) {
 // determines whether the token is present, then if there is a normal jump 
IF (localStorage. the getItem ( ' token ' )) { 
Next () 
} the else { 
Next ( ' / Login ' ) 
} 
} the else { 
Next () 
} 
})

 Here we list only a portion of the code, check out the full amount of the code.

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import StudentsInfo from '@/components/StudentsInfo'
import Login from '@/components/Login'

Vue.use(Router)

let router = new Router({
  routes: [{
      path: '/',
      name: 'HelloWorld',
      Component: the HelloWorld 
    }, 
    { 
      path: ' / StudentsInfo ' , 
      name: ' StudentsInfo ' , 
      Component: StudentsInfo 
    }, 
    { 
      path: ' / the Login ' , 
      name: ' the Login ' , 
      Component: the Login 
    } 
  ] 
}) 

// Navigation guard
 / / using a global front guard router.beforeEach register determines whether the user login 
router.beforeEach ((to, from , Next) => {
   iF (to.path === ' / the login ') {

    next();
  } else {
    let token = localStorage.getItem('Authorization');
    if (token === null || token === '') {
      next('/Login');
    } else {
      next();
    }
  }
});

export default router;

 


2. The successful login, the token store

Login () {
 // initiation request log 
axios.post ( ' / User / Login ' , the this the .user) .then (RES => { 
the console.log (res.data) 
// receiving the token stored in the token after localstorage
 // prefix must be added 
localStorage.setItem ( ' token ' , " Bearer " + res.data.res.token) 
}) 
}

 


3. Set request interceptor
 

As long as each token carries a token request let 

// setting request interceptor 
axios.interceptors.request.use (config => {
 // the console.log (config) 
const token = localStorage.getItem ( ' token ' )
 IF ( token) {
 // the acquired token to the Authorization header is provided in 
config.headers.Authorization = token 
} 
return config 
})

 

Setting response blocker 4

In response to a result of processing, token problems, it must be returned 401 

// setup response blocker 
axios.interceptors.response.use (RES => {
 // process the results 
IF (res.data.res_code === 401 ) {
 // jump log 
router.replace ( ' / Login ' )
 // delete token 
localStorage.removeItem ( ' token ' ) 
} 
return RES 
}, ERR => {
 // if the interface is normal, will go err, err.response .status 401 is operated to delete the token and jump 
})

Guess you like

Origin www.cnblogs.com/sexintercourse/p/12449667.html