Token verification login in Vue project (front-end part)

Token verification login in Vue project (front-end part)

This article example shares the specific code of token verification login in the Vue project for your reference. The specific content is as follows

1. Introduction

I am currently working on my graduation project. I am working on the backend and do not know much about the frontend. I have been looking at the Vue framework for nearly two weeks before I feel a little bit of a beginner. Therefore, this article may not be well written. It is just a record. If there is anything wrong or insufficient, please point it out.

2. Problem

When making a login interface, I chose to use token to verify the login. The front-end framework I used was Vue.js and element-ui. How to use token to verify the login in vue.

3. Thinking

1. Use token to verify login. When the user logs in, the backend will generate a token and return it to the frontend. The frontend will put the token in the request header (this is Baidu's, generally it is put in the request header), and then call the interface to put the token in the request header and return it to the backend;
2. After the user logs in, the front end needs to save the token and take it out when sending a request later;
3. Add the token to the request header when sending each request and write a global interceptor.

4. Records and instructions

1. Create a store folder under the src folder (my vue project is created with vue-cli scaffolding) and create an index.js in the store

2. src/store/index.js

import Vue form 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
 state: {
  token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
 },
 mutotions:
  setToken (state,token) {
   state.token =token;
   localStorage.setItem("token",token.token);
  },
  delToken(state) {
   state.token = '';
   localStorage.removeItem("token");
  }
 }
})

export default store;

illustrate:

(1) Before writing the content in src/store/index.js, you need to install Vuex in your project. Here we only provide the npm installation method. Open cmd in the project root directory and enter the following command, then press Enter

npm install vuex --save

(2) In this store/store/index.js, the code token.token is because when calling this method in login.vue, an object is passed in (even if you think you passed in a string, you don’t know why it is put into the object), and the object passed in has the attribute token.

localStorage.setItem("token",token.token);

3. src/main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import promise from 'es6-promise'
import store from './store/index'
promise.polyfill()

Vue.use(ElementUI)
Vue.config.productionTip = false
 

axios.defaults.baseURL = 'http://192.168.80.152:8088'
axios.defaults.headers.post['Content-Type'] = "application/json"
axios.defaults.withCredentials = true
axios.defaults.headers.common['Authorization'] = store.state.token
Vue.prototype.$axios = axios
 

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});

// Add request interceptor axios.interceptors.request.use(config => {
// What to do before sending a request // Check if a token exists, and if so, add a token to each page header
  if (store.state.token) {
    config.headers.common['Authorization']=store.state.token.token
  }

  return config;
}, error => {
// Do something 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:
          this.$store.commit('del_token');
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//After successful login, jump to the current page being browsed})
      }
    }
    return Promise.reject(error.response.data)
  });

illustrate

(1) This is the complete code. It may not be the same as this one. Let’s talk about using token verification. What should be configured in src/main.js? (2)

import store from './store/index'

The above code imports the previously written src/store/index.js into main.js

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});

The store in the above code is mounted on Vue, and then this.$store can be used to get the store

(3)

// Add request interceptor axios.interceptors.request.use(config => {
// What to do before sending a request // Check if a token exists, and if so, add a token to each page header
  if (store.state.token) {
    config.headers.common['Authorization']=store.state.token.token
  }

  return config;
}, error => {
// Do something 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:
          this.$store.commit('del_token');
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//After successful login, jump to the current page being browsed})
      }
    }
    return Promise.reject(error.response.data)
  });

The above code is a request interceptor that puts the token in the request header of the request

4. src/router/index.js

router.beforeEach((to, from, next) => {
  if(to.path === '/login') {
    next();
  } else {
    let token = localStorage.getItem('token');
    if(token === 'null' || token === '') {
      next('/login');
    }else {
      next();
    }
  }
});

illustrate

(1) The above code is the configuration of src/router/index.js. The router needs to be exposed. There is export default in the code.

**5. src/components/login/login.vue **

//Introduce something on the export default of this component script tag import { mapMutations } from 'vuex';
//This is the methods part methods: {

      ...mapMutations(['setToken']),
      login(form){


        let _this = this;
        if(form.phone === "" || form.password === ""){
          _this.$message.error("Please enter your phone number or password");
        }else {
          this.$axios.post(`/user/check/login`,_this.form).then(res => {
            var code = res.data.code;
            var mes = res.data.message;
            if(code === 1){
             /* storage.setItem("token",res.data.data);
              _this.token = res.data.data;*/
             // _this.setToken({Authorization: _this.token})
             // console.log("success");
              _this.$message.success('Login successful');
              _this.token = res.data.data;
              _this.setToken({token: _this.token});
              _this.$router.push({path:"/home"});

              var storage = window.localStorage;
              //alert(storage.getItem("token"));

              if(this.$store.state.token) {
                this.$router.push('/home');
                console.log(this.$store.state.token.token);
              } else {
                this.$router.replace('/login');
              }

            }else{
              _this.$message.error(mes);
            }
          }).catch(function(err){
            console.log(err);
            _this.$message.error("Login error, please contact the program developer!!");

          })
        }

      }
     }

illustrate

(1)

let _this = this;

The above code puts this in the variable _this. There are two types of functions: ordinary functions: function(){} and arrow functions. The this of ordinary functions refers to the reference of the current object. The current object here is uncertain. The this of arrow functions is a global one. The object represented by this is immutable and cannot be changed in any way. For the specific difference, see: The difference between arrow functions and ordinary functions

 _this.setToken({token: _this.token});

The above code calls the setToken() method in src/store/index.js. The reason why it can be called with _this is because the store was mounted on vue in src/main.js before.

...mapMutations(['setToken']),

There is a piece of code in front of the login() method in src/components/login/login.vue. I don't know what it does. It may be a method in the specified score. This is my guess based on the parameters in it. It may not be correct. I hope someone can give me some advice.

The following are reference articles, all of which are well written.

1. How to get token in Vue and write it into header
2. Implement user login and token verification in Vue project

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 token login 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

<<:  VMware vCenter 6.7 installation process (graphic tutorial)

>>:  Detailed tutorial on installing qt5.12.8 and environment configuration on ubuntu18.04

Recommend

Version numbers in css and js links in HTML (refresh cache)

background Search the keyword .htaccess cache in ...

Tomcat obtains the client domain name of Nginx reverse proxy

question After Nginx reverse proxy, the Tomcat ap...

Docker image export, import and copy example analysis

The first solution is to push the image to a publ...

How to set up cross-domain access in IIS web.config

Requirement: The page needs to display an image, ...

Detailed explanation of several ways to export data in Mysql

There are many purposes for exporting MySQL data,...

Understanding JSON (JavaScript Object Notation) in one article

Table of contents JSON appears Json structure Jso...

Installation and use of mysql mycat middleware

1. What is mycat A completely open source large d...

Solution to EF (Entity Framework) inserting or updating data errors

Error message: Store update, insert, or delete st...

Web page text design should be like smart girls wearing clothes

<br />"There are no ugly women in the w...

Details of using Vue slot

Table of contents 1. Why use slots? 1.1 slot 1.2 ...

Axios cancel request and avoid duplicate requests

Table of contents origin status quo Cancel reques...

Solve the problem of Mac Docker x509 certificate

question Recently I needed to log in to a private...

Detailed explanation of .bash_profile file in Linux system

Table of contents 1. Environment variable $PATH: ...

Sample code on how to implement page caching in vue mobile project

background On mobile devices, caching between pag...

Mysql 5.6 "implicit conversion" causes index failure and inaccurate data

background When performing a SQL query, I tried t...