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

Initial summary of the beginner's website building tutorial

After writing these six articles, I started to fee...

Install Linux using VMware virtual machine (CentOS7 image)

1. VMware download and install Link: https://www....

Implementation of docker redis5.0 cluster cluster construction

System environment: Ubuntu 16.04LTS This article ...

Detailed explanation of the use of docker tag and docker push

Docker tag detailed explanation The use of the do...

Example code for mixing float and margin in CSS

In my recent studies, I found some layout exercis...

Detailed installation instructions for the cloud server pagoda panel

Table of contents 0x01. Install the Pagoda Panel ...

Summary of Linux file directory management commands

touch Command It has two functions: one is to upd...

Detailed explanation of the installation and use of Vue-Router

Table of contents Install Basic configuration of ...

How to uninstall MySQL 5.7 on CentOS7

Check what is installed in mysql rpm -qa | grep -...

How to set up the use of Chinese input method in Ubuntu 18.04

In the latest version of Ubuntu, users no longer ...

Example code for implementing dynamic skinning with vue+element

Sometimes the theme of a project cannot satisfy e...

Detailed explanation of using echarts map in angular

Table of contents Initialization of echart app-ba...