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

Teach you how to quickly enable self-monitoring of Apache SkyWalking

1. Enable Prometheus telemetry data By default, t...

Application examples of WeChat applet virtual list

Table of contents Preface What is a virtual list?...

Analyze the selection problem of storing time and date types in MySQL

In general applications, we use timestamp, dateti...

Nginx prohibits direct access via IP and redirects to a custom 500 page

Directly to the configuration file server { liste...

Docker and portainer configuration methods under Linux

1. Install and use Docer CE This article takes Ce...

How to connect to MySQL database using Node-Red

To connect Node-red to the database (mysql), you ...

JavaScript operation element examples

For more information about operating elements, pl...

Detailed explanation of dynamically generated tables using javascript

*Create a page: two input boxes and a button *Cod...

5 MySQL GUI tools recommended to help you with database management

There are many database management tools for MySQ...

mysql splits a row of data into multiple rows based on commas

Table of contents Separation effect Command line ...

Parameters to make iframe transparent

<iframe src="./ads_top_tian.html" all...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

How to change the domestic image source for Docker

Configure the accelerator for the Docker daemon S...

Ubuntu regularly executes Python script example code

Original link: https://vien.tech/article/157 Pref...