Call up the login interface (first clarify what to do)

In the case of complete separation of the front and back ends, the general idea of token verification in Vue project is as follows:

  1. When logging in for the first time, the front-end invokes the login interface of the back-end and sends the user name and password
  2. The back end receives the request, verifies the username and password, and returns a token to the front end
  3. The front-end gets the token, stores the token in localStorage and VUEX, and jumps to the routing page
  4. Each time the front end jumps to a route, it determines whether there is a token in localStroage. If there is no token in localStroage, it jumps to the login page; if there is, it jumps to the corresponding route page
  5. Add a token to the request header each time the back-end interface is invoked
  6. The backend checks whether there is a token in the request header. If there is a token, the backend gets the token and verifies the token. If the verification is successful, the data is returned
  7. If the front-end gets the status code 401, the token information is cleared and the login page is redirected
  8. If the login interface is successfully accessed, the token is stored in localStorage and VUEX in the callback function

First, preliminary preparation

The page template

<template> <div> <input type="text" V-model ="loginForm. Username "placeholder=" placeholder "/> <input type="text" /> <button @click="login"> </button> </div> </template>Copy the code

Logic implementation

export default { data() { return { loginForm: { username: "", password: "", }, }; }, methods: { ... mapMutations(["changeLogin"]), login() { let _this = this; / / / / / interpretation whether account password input, no can alert the if (this. LoginForm. Username = = = "" | | this. LoginForm. Password = = =" ") {alert (" account or password cannot be empty "); } else { this.axios({ method: "post", url: "/user/login", data: _this.loginForm, }) .then((res) => { console.log(res.data); _this.userToken = "Bearer " + res.data.data.body.token; _this.changelogin ({Authorization: _this.usertoken,}); _this.$router.push("/home"); Alert (" login successful "); }). Catch ((error) => {alert(" error "); console.log(error); }); ,}}}};Copy the code

3. Add the token in index.js in the store folder

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); Const store = new vuex.store ({state: {// Store token Authorization: localstorage.getitem ('Authorization')? localStorage.getItem('Authorization') : '' }, mutations: {// Modify the token and store the token in localStorage changeLogin (state, user) {state.authorization = user.authorization; localStorage.setItem('Authorization', user.Authorization); }}}); export default store;Copy the code

Second, configure the route navigation guard

Index.js in the router folder

import Vue from 'vue'; import Router from 'vue-router'; import login from '@/components/login'; import home from '@/components/home'; Vue.use(Router); const router = new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: login }, { path: '/home', name: 'home', component: home } ]}); // Navguard // Registers a global front-guard with router.beforeeach, Determine whether a user is logged in to the router. BeforeEach ((to, from, next) => {if (to.path === '/login') {next(); } else { let token = localStorage.getItem('Authorization'); if (token === 'null' || token === '') { next('/login'); } else { next(); }}}); export default router;Copy the code

Request header token added in main.js

// Add request interceptor, Add token to the request header axios. Interceptors. Request. Use (config = > {the if (localStorage. The getItem (" Authorization ")) { config.headers.Authorization = localStorage.getItem('Authorization'); } return config; }, error => { return Promise.reject(error); });Copy the code

The expiration of the token can be customized

4. If the front end gets the status code 401, clear the token information and jump to the login page

localStorage.removeItem('Authorization'); this.$router.push('/login');
Copy the code