Vue project realizes user login and token verification
In the case of complete separation of the front and back ends, the general idea of token verification in Vue project is as follows:
- 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
- The back end receives the request, verifies the username and password, and returns a token to the front end
- The front-end gets the token, stores the token in localStorage and VUEX, and jumps to the routing page
- 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
- Add a token to the request header each time the back-end interface is invoked
- 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
- If the front-end gets the status code 401, the token information is cleared and the login page is redirected
-
The login interface is successfully invoked. The token is stored in localStorage and VUex in the callback function
<template> <div> <input type="text" V-model ="loginForm. Username "placeholder=" placeholder "/> <input type="text" V-model ="loginForm. Password "placeholder=" password" /> <button @click="login"> </button> </div> </template> <script> import { mapMutations } from 'vuex'; export default { data () { return { loginForm: { username: '', password: '' } }; }, methods: { ... mapMutations(['changeLogin']), login () { let _this = this; 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(' account or password error '); console.log(error); }); }}}}; </script>Copy the code
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
-
Route navigation guard
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 with token
// 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
-
If the front-end gets the status code 401, the token information is cleared and the login page is redirected
localStorage.removeItem('Authorization');
this.$router.push('/login');
Copy the code
NavigationDuplicated vue-Router routing error is reported
-
Problems with the new router:
Solution: Reduce the version
npm i vue-router@3.0 -S
Copy the code
-
Using the new version of the solution:
Add the following code to main.js:
import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
Copy the code
If your push still doesn’t work, consider replacing
Modified the route replace method to prevent repeated clicks from reporting errors
const originalReplace = Router.prototype.replace;
Router.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
};
Copy the code