VUE implements token login verification

VUE implements token login verification

This article example shares the specific code of VUE to implement token login verification for your reference. The specific content is as follows

The process of implementing this login function was full of twists and turns. A bug appeared in the middle and it took two or three days to solve the problem. I was exhausted and overwhelmed. I felt that my perseverance and patience had been raised to a new level.

Fortunately, I finally solved the bug with the help of my classmates, but I once again felt the shallowness of being a rookie. The questions asked by the big guys repeatedly touched my blind spots in knowledge... Now I will record the steps to implement token login verification in detail to prevent making mistakes in the future.

1. Encapsulate the store's operation method on token

First, create a store folder in the src directory, and then create a main.js file

The code stored in main.js is used to obtain the value of token and store and delete the value of local token using localStorage.

import Vue from 'vue';
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
  },
  mutations:
    setToken (state,token) {
      state.token =token;
      localStorage.setItem("token",token.token); //Store token
    },
    delToken(state) {
      state.token = '';
      localStorage.removeItem("token"); //Delete token
    }
  }
})

2. Connect to the login interface on the page for verification

Log in

(1) Input box code

<input type="text" v-model="username" placeholder="Username" />
<input type="password" v-model="password" placeholder="password"/>

(2) Script code

<script>
  import { mapMutations } from 'vuex';
  export default {
    name: "managerLogin",
    data() {
      return {
        username:'', //usernamepassword:'', //password};
    },
    methods:{
      ...mapMutations(['setToken']),
      login:function() {
        if (this.username === '' || this.password === '') {
          alert("Account or password cannot be empty!");
        }
        else {
          //According to the API interface to obtain the token
          this.$ajax.get('http:///api/wx/Public/login', {
            params: { //Incoming parameters username: this.username, password: this.password, device_type: "mobile"
            }
          }).then(
            res => {
              console.log(res.data);
              if(res.data.code===1) { //If code=1, verification is successful this.setToken({token: res.data.data.token}); //Method for assigning token in store this.$router.push('/managerHome');
              }
              else{
                alert(res.data.msg); //Popup error message}
            }).catch(error => {
            alert('Interface connection error');
            console.log(error);
          });
 
        }
      }
  }
</script>

Log out

<script>
    import {mapMutations} from "vuex";
    export default {
      name: "manager_infor",
      methods:{
        ...mapMutations(['delToken']),
        exit:function(){
          this.delToken({token:''});
          this.$router.push('/managerLogin');
        }
      }
    }
</script>

3. Routing Guard

This code is placed in the routing file. Its function is to check the locally stored token value for login verification before the page jumps to determine whether to jump

router.beforeEach((to, from, next) => {
  if (to.path === '/managerLogin') { //If the page to be jumped is the login interface next(); //jump directly}
  else if (to.path === '/managerHome'){ //If the page to be jumped is the personal interface let token = localStorage.getItem('token'); //Get the token value stored locally if (token===null||token===''){ //If the token is empty, the verification fails and jumps to the login page next('/managerLogin');
    }
    else{ //If it is not empty, the verification is successful next();
    }
  }
  else{
    next();
  }
});
 
export default router;

4.Axios request interceptor

This code is placed in the main.js file under the src file

import axios from "axios";
import store from './store/main';
Vue.prototype.$ajax = axios
 
new Vue({
  el: '#app',
  router,
  store, //store needs to be added components: { App },
  template: '<App/>'
})
 
//Request interceptor axios.interceptors.request.use(config => {
// Check if a token exists. If so, add the token to the header of each page.
  if (store.state.token) {
    
    config.headers.common['XX-Token']=store.state.token //The XX-Token here should be written according to the name of the request header in the login interface}
 
  return config;
}, error => {
// Request error return Promise.reject(error);
});
 
//response interceptor axios.interceptors.response.use(
  response => {
    return response;
  },
  
  error => { //By default, all errors except 2XX are considered errors if (error.response) {
      switch(error.response.status){
        case 401:
          this.$store.commit('delToken');
          router.replace({ //Jump to the login page path: '/managerLogin',
            query: { redirect: router.currentRoute.fullPath } // Take the redirected route path as a parameter and jump to the route after successful login});
      }
    }
    return Promise.reject(error.response);
  }
);

Mission accomplished!

I'll post the data structure of my backend interface for reference. The above code will be slightly different when using different interfaces, so you need to know how to use it flexibly.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue implements user login and token verification
  • Vue implements login verification code
  • Vue login sliding verification implementation code
  • Use vue-route's beforeEach to implement navigation guard (verify login before route jump) function
  • Vue actual combat vue login verification implementation code
  • Vue login registration and token verification implementation code
  • How to implement the verification login status in Vue
  • vue router+vuex implements home page login verification logic
  • An example of Vue using the routing hook to jump to the login page after the token expires
  • Token verification login in Vue project (front-end part)

<<:  MySQL 8.0.19 winx64 installation tutorial and change the initial password under Windows 10

>>:  Docker builds the code detection platform SonarQube and detects the process of Maven projects

Recommend

How to remove MySQL from Ubuntu and reinstall it

First delete mysql: sudo apt-get remove mysql-* T...

Detailed explanation of Nginx status monitoring and log analysis

1. Nginx status monitoring Nginx provides a built...

Solution to installing vim in docker container

Table of contents The beginning of the story Inst...

Steps to install cuda10.1 on Ubuntu 20.04 (graphic tutorial)

Pre-installation preparation The main purpose of ...

How to use the concat function in mysql

As shown below: //Query the year and month of the...

Use pure CSS to achieve scroll shadow effect

To get straight to the point, there is a very com...

Detailed explanation of various join summaries of SQL

SQL Left Join, Right Join, Inner Join, and Natura...

Tutorial on installing Elasticsearch 7.6.2 in Docker

Install Docker You have to install Docker, no fur...

Install mysql5.7.13 using RPM in CentOS 7

0. Environment Operating system for this article:...

Solve the problem of running jupyter notebook on the server

Table of contents The server runs jupyter noteboo...

CSS Naming: BEM, scoped CSS, CSS modules and CSS-in-JS explained

The scope of css is global. As the project gets b...

Implementation of nginx flow control and access control

nginx traffic control Rate-limiting is a very use...