Detailed explanation of the configuration method of Vue request interceptor

Detailed explanation of the configuration method of Vue request interceptor

Follow the steps below

1. request.js content: http request interceptor and http response server response interceptor configuration

2. http.js content: request data encapsulation

3. utils.js content: Get token and determine whether token exists

4. store file:

vuex warehouse configuration

  • vuex persistence
  • Vuex template reference

5. Interface encapsulation

Table of contents

request.js content

http request request interceptor and http response response interceptor configuration

 // http request interceptor, if there is a token value, configure the token value import axios from 'axios'
import Promise from 'promise'
import util from './utils';
import store from './../store/index';
const service = axios.create({
    timeout: 60000, // request timeout headers: {
        // Authorization: Authorization,
        'Content-Type': 'application/json;charset=UTF-8'
    }
});
// http request interceptor service.interceptors.request.use(
    config => {
        let tokenExist = util.tokenExist();
        if (tokenExist) {
            // bus.$emit('toggleloading', true) //display loading
            //If token exists config.headers['Authorization'] = `Bearer ${util.getToken()}`;
        }
        // Toast.loading({
        // message: 'Loading...',
        // duration: 0,
        // forbidClick: true
        // });
        return config;
    },
    error => {
        Promise.reject(error);
    }
)
// http response server response interceptor,
//Intercept 401 errors here and jump back to the login page to get the token again
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            //Communication successful// Toast.clear();
            /****************
             * response.data.status === 0 Error* response.data.status === 100 Success* response.data.status === 401 Token expired*
             * *************/
            // bus.$emit('toggleloading', false) // Hide loading
            if (response.data.state === 401) {
                //If the token is expired, jump to login Message.error("Login has expired, please log in again!");
                store.commit('SET_TOKEN', '');
                util.goLogin();
            } else if (response.data.state === 0) {
                // Message.error(response.data.message);
                return response.data;
            } else {
                return response.data;
            }
        }
    },
    error => {
        //Request failed//;
        const response = error.response;
        if (response.status === 401) {
            // Toast.fail(response.data.message);
            Message.error("Login has expired, please log in again!");
            util.goLogin();
        } else if (response.status === 403) {
            $router.push({
                name: '403'
            });
        } else {
            // Toast.fail(response.data.message ? response.data.message : 'System error, please contact the administrator');
            // Message.error({
            // message: 'No service, please contact the administrator'
            // });
        }
        return Promise.reject(error);
    }
);
export default service;

http.js content

Request data method

 import request from './request';
// import store from './../store/index';
const http = {
    request(config) {
        request(config);
    },
    post(url, data) {
        // if (data instanceof Object) {
        // }else{
        // data = {
        // ...data
        // };
        // }
        return request({
            url,
            method: 'post',
            data
        });
    },
    postFile(url, data, contentType) {
        return request({
            url,
            method: 'post',
            data,
            contentType
        });
    },
    get(url, params) {
        return request({
            url,
            method: 'get',
            params
        });
    },
    put(url, data) {
        return request({
            url,
            method: 'put',
            data
        });
    },
    delete(url) {
        return request({
            url,
            method: 'delete'
        });
    },
    download(url, params) {
        return request({
            url,
            method: 'get',
            params,
            responseType: 'blob'
        });
    },
    downloadPost(url, data) {
        return request({
            url,
            method: 'post',
            data,
            responseType: 'blob'
        });
    }
};
export default http;

utils.js content

Get the token and determine whether the token exists

 import store from '../store/index';
let util = {
    //Get token
    getToken() {
        return store.getters.token;
    },
    //Judge whether the token exists tokenExist() {
        let flag;
        let token = store.getters.token;
        if (token && token !== '') {
            flag = true;
        } else {
            flag = false;
        }
        return token;
    },
}
export default util 

vuex warehouse configuration

  • vuex persistence
  • Vuex template reference

index.js content

 import Vue from "vue"
import Vuex from "vuex"
import VuexPersistence from 'vuex-persist';
import db from './db'
Vue.use(Vuex)
//vuex state persistence const vuexLocal = new VuexPersistence({
    storage:window.localStorage
})
const store = new Vuex.Store({
    state:{},
    mutations:{},
    actions:{},
    modules:{
        db
    },
    plugins:[vuexLocal.plugin]
})
export default store

db.js content

 const db = {
    state: {
        token: '',
    },
    getters:{
        token:state => state.token
    },
    mutations:
        //Store token
        setToken: (state, value) => {
            state.token = value
        }
    },
    actions: {}
}
export default db

Interface encapsulation

 import http from "../common/http"
/***********Login and register*************/
//Test interface function text(params){
    return http.get("api/Test/GetList", params)
}
//Login function Login(params) {
    return http.post("api/Login/Login", params)
}
// Get the graphic verification code function GetValidateCode(params) {
    return http.post("api/Login/GetValidateCode", params)
}
// Get the phone verification code Note: You need to verify the human-machine verification in advance, otherwise there is a risk of being maliciously swiped by SMS function GetPhoneCode(params) {
    return http.post("api/Login/GetPhoneCode", params)
}
//Registration verification information function RegisterUserVerify(params) {
    return http.post("api/Login/RegisterUserVerify", params)
}
// Register, set password and register user information function RegisterUserInfo(params) {
    return http.post("api/Login/RegisterUserInfo", params)
}
// Forgot password verification name and phone number function ResetPasswordVerify(params) {
    return http.post("api/Login/ResetPasswordVerify", params)
}
// Forgot password Password update function ResetPassWord(params) {
    return http.post("api/Login/ResetPassWord", params)
}
export {
    Login,
    text,
    GetPhoneCode,
    RegisterUserVerify,
    GetValidateCode,
    ResetPasswordVerify,
    ResetPassWord,
    RegisterUserInfo
}

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Vue adds request interceptor and vue-resource interceptor usage
  • Vue axios login request interceptor
  • Summary of knowledge points of Vue routing interceptor and request interceptor
  • Steps for Vue to encapsulate Axios requests and interceptors
  • Vue axios interceptor commonly used repeated request cancellation

<<:  Hover zoom effect made with CSS3

>>:  Seven different color schemes for website design experience

Recommend

WeChat applet realizes the effect of swiping left to delete list items

This article shares the specific code for WeChat ...

MySQL table return causes index invalidation case explanation

Introduction When the MySQL InnoDB engine queries...

Basic use of javascript array includes and reduce

Table of contents Preface Array.prototype.include...

...

How to test network speed with JavaScript

Table of contents Preface Summary of the principl...

Detailed tutorial on installing MySQL 8 in CentOS 7

Prepare Environmental information for this articl...

How to change the host name in Linux

1. View the current host name [root@fangjian ~]# ...

Win10 + Ubuntu20.04 LTS dual system boot interface beautification

Effect display The built-in boot interface is too...

VMware virtualization kvm installation and deployment tutorial summary

Virtualization 1. Environment Centos7.3 Disable s...

Vue implements login jump

This article example shares the specific code of ...

Implementing license plate input function in WeChat applet

Table of contents Preface background Big guess Fi...