Vue gets token to implement token login sample code

Vue gets token to implement token login sample code

The idea of ​​using token for login verification is as follows:

1. When logging in for the first time, the front end calls the back end interface and passes the username and password to the back end.

2. The backend receives the request, verifies the username and password, and returns a token value to the frontend after successful verification.

3. The front end receives the token value passed by the back end and stores the token in local loaclStorage and vuex. (This project uses the vue framework and vuex global state management)

4. Every time the front-end route jumps, it determines whether there is a token in localStorage. If not, it jumps to the login page. If so, it jumps to the corresponding page.

5. Package a public request interface method, and bring the token in the request header every time you request to call the backend interface

6. The backend determines whether there is a token in the request header. If there is a token, it gets the token and verifies the token. If the verification is successful, the data is returned. If the verification fails (for example, the token expires), a status code is returned to the frontend, usually 401. If there is no token in the request header, 401 is also returned. (Step 6 is done by the backend, and the frontend only needs to process the status returned by the backend accordingly.)

7. If the status code returned by the front-end backend is 401, clear the token and jump to the login page.

Practical steps

1. Add global methods for saving and deleting tokens in the store.js file in the project store.

// In store.js, add methods to add and delete tokens in mutation import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = { // Globally managed data storage isLogin:'0',
	 ser:null,
	 token:localStorage.getItem('token') ? localStorage.getItem('token'):'', // token
};
export default new Vuex.Store({
	state,
	getters:{ // Listen for data changes getStorage(state){ // Get the login information stored locally if(!state.token){
	        state.token = JSON.parse(localStorage.getItem(key))
	      }
	      return state.token
	    }
	},
	mutations:
		$_setToken(state, value) { // Set storage token
	        state.token = value;
	        localStorage.setItem('token', value);
	    },
	    $_removeStorage(state, value){ // delete token
		      localStorage.removeItem('token');
	    },
	}
})

2. After the login method in the login page (login.vue) successfully calls the interface, the token is stored in the local storage localStorage.

// login.vue page methods:{
	loginFun(){
		this.$api.post('requested backend interface link',{
				data:{
					userId:this.user, // login name userPwd:this.psw, // login password }
		}).then((res) => {
			if(res.data.status == 200){
				var userInfo = res.data.data;
				this.$store.commit('$_setToken', userInfo.token);
				Toast({ message: 'Login successful', type: 'success', duration: 1500}); // UI pop-up window prompt this.$router.push({ name:'homePage' }); // Jump to the home page } else {
				Toast({ message: res.data.message, duration: 1500}); // UI pop-up window prompt }
		})
	}
}

3. Add a request interceptor in main.js and add a token to the request header.

import Vue from 'vue'
import App from './App.vue'
import router from './router/router'
import store from './store/store'

import PublicFun from './utils/publicFun' // Public method import './mintUi' // Import mintUi components as needed. If necessary, configure them in mintUi.js. import '@/assets/mui/css/mui.css' // mui.css style /* Import axios plug-in */
import axios from 'axios'
Vue.prototype.$http = axios;

// Global routing constructor, determine whether to log in and jump to the page router.beforeEach((to, from, next) => {
  if (to.matched.some(m => m.meta.requireAuth)) { // Need to log in if(window.localStorage.token && window.localStorage.isLogin === '1'){
      next()
    } else if (to.path !== '/login') {
      let token = window.localStorage.token;
      if (token === 'null' || token === '' || token === undefined){
          next({path: '/login'})
          Toast({ message: 'It is detected that you are not logged in, please log in before operating!', duration: 1500 })
      }
    } else {
      next()
    }
  } else { // No need to log in next()
  }
})



//Configure public url
Axios.defaults.baseURL = "http://www.sinya.online/api/"
//Add request interceptor axios.interceptors.request.use(
  config =>{
    if (store.state.token) {
      config.headers.common['token'] = store.state.token
    }
    return config;
  },
  error =>{
    //What to do with request error return Promise.reject(error);
  })

//http response interceptor axios.interceptors.response.use(
  response =>{
    return response;
  },
  error=>{
    if (error.response) {
      switch(error.response.status){
        case 401:
          localStorage.removeItem('token');
          router.replace({
            path: '/views/login',
            query: {redirect: router.currentRoute.fullPath}//After successful login, jump to the current page being browsed})
      }
    }
  })

Vue.prototype.$publicFun = PublicFun // Mount global public method Vue.prototype.$apps = Apps // app.js public method Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

See the token

insert image description here

When exiting

returnFun(){ // Log out MessageBox.confirm(this.lang.logoutTip).then(action => {
	     this.$store.commit('$_removeStorage'); // Clear login information this.$router.push({
	         name:'login'
	     });
	     Toast({message:this.lang.logoutSuccess, duration: 1500});
	 }).catch(()=>{})
} 

This is the end of this article about the sample code of vue getting token to implement token login. For more relevant vue token login content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue implements automatic jump to login page when token expires
  • Token verification login in Vue project (front-end part)
  • Vue implements user login and token verification
  • VUE implements token login verification
  • Vue login registration and token verification implementation code

<<:  Use the CSS Paint API to dynamically create resolution-independent, variable background effects

>>:  7 skills that great graphic designers need to master

Recommend

Detailed tutorial on installing Tomcat9 windows service

1. Preparation 1.1 Download the tomcat compressed...

How Web Designers Create Images for Retina Display Devices

Special statement: This article is translated bas...

Detailed explanation of common usage of MySQL query conditions

This article uses examples to illustrate the comm...

Processing ideas for decrypting WeChat applet packages on PC in node.js

Table of contents Where is the source code of the...

MySQL query specifies that the field is not a number and comma sql

Core SQL statements MySQL query statement that do...

Example of using Docker to build an ELK log system

The following installations all use the ~/ direct...

CSS code for arranging photos in Moments

First, you can open Moments and observe several l...

Install Tomcat on Linux system and configure Service startup and shutdown

Configure service startup and shutdown in Linux s...

What is flex and a detailed tutorial on flex layout syntax

Flex Layout Flex is the abbreviation of Flexible ...

Is it necessary to give alt attribute to img image tag?

Do you add an alt attribute to the img image tag? ...

Navicat imports csv data into mysql

This article shares with you how to use Navicat t...

In-depth analysis of Flex layout in CSS3

The Flexbox layout module aims to provide a more ...

Detailed explanation of various HTTP return status codes

When a request is sent to your server to display ...