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

Disable IE Image Toolbar

I just tried it on IE6, and it does show the toolb...

Example of using CSS to achieve semi-transparent background and opaque text

This article introduces an example of how to use ...

How to disable the automatic password saving prompt function of Chrome browser

Note: In web development, after adding autocomplet...

Understand the initial use of redux in react in one article

Redux is a data state management plug-in. When us...

Summary of how to add root permissions to users in Linux

1. Add a user . First, use the adduser command to...

Simple web page code used in NetEase blog

How to use the code in NetEase Blog: First log in...

How to export and import .sql files under Linux command

This article describes how to export and import ....

Deploy Confluence with Docker

1. Environmental requirements 1. Docker 17 and ab...

Query the data of the day before the current time interval in MySQL

1. Background In actual projects, we will encount...

How to modify the user and group of a file in Linux

In Linux, when a file is created, the owner of th...