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

Install mysql5.7.17 using RPM under Linux

The installation method of MySQL5.7 rpm under Lin...

JavaScript Function Currying

Table of contents 1 What is function currying? 2 ...

A brief discussion on docker-compose network settings

Networks usage tutorial Official website docker-c...

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

Pre-installation preparation The main purpose of ...

Detailed example of reading speed of js objects

1. Accessing literals and local variables is the ...

CSS realizes div completely centered without setting height

Require The div under the body is vertically cent...

Vue uses dynamic components to achieve TAB switching effect

Table of contents Problem Description What is Vue...

Troubleshooting ideas and solutions for high CPU usage in Linux systems

Preface As Linux operation and maintenance engine...

How to add conditional expressions to aggregate functions in MySql

MySQL filtering timing of where conditions and ha...

js to realize a simple advertising window

This article shares the specific code of js to im...

Detailed explanation of the function and usage of keepAlive component in Vue

Preface During the interview, many interviewers m...

The difference between Readonly and Disabled

To summarize: Readonly is only valid for input (te...

Detailed graphic explanation of sqlmap injection

Table of contents 1. We found that this website m...