stay vue in , You can use it **Storage(sessionStorage,localStorage)** To store token, It can also be used vuex To store ( But we should consider the problem of page refresh and data disappearance , Can be in vuex use Storage), Here is how to use localStorage To store :

After successful login request , Will return a token value , use loaclStorage preservation
localStorage.setItem('token',res.data.token)
stay main.js The judgment of setting global request header and response return in
// set up axios Request header join token Axios.interceptors.request.use(config => { if (config.push
=== '/') { } else { if (localStorage.getItem('token')) {
// Add in request header token, The name should be the same as that of the request header received by the back end token The same name config.headers.token=localStorage.getItem(
'token'); } } return config; }, error => { return Promise.reject(error); });
//============================= // Respond back token Is it overdue Axios.interceptors.response.use(
response=> { console.log(' Respond back :'+response.data.code) // And back end token Invalid return code Convention 403 if (
response.data.code == 403) { // quote elementui message prompt box ElementUI.Message({
message: ' The identity is invalid ', type: 'err' }); // eliminate token localStorage.removeItem('token ');
// Jump router.push({name: 'login'}); } else { return response } }, error => {
return Promise.reject(error); })
stay router In index Set the global guard to determine whether it exists token, If it doesn't exist, return to the login page
router.beforeEach((to, from, next) => { //to Where to from Where to leave next Jump Empty means release if (to.
path=== '/') { // If jump to login , Let it go next(); } else { // take out localStorage judge let token =
localStorage.getItem('token '); if (token == null || token === '') { console.log
(' Please log in first ') next({name: 'login'}); } else { next(); } }});

Technology