Learn how to encapsulate Axios

Step 1: Introduce Axios

import axios from 'axios 
Copy the code

Step 2: Create an AXIOS instance and set the request header

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,  // Distinguish the environment
    timeout: 50000
});
Copy the code

Step 3: Request interceptor

service.interceptors.request.use(
    config= > {
        // You can add this if you want to cancel the request
        //config.cancelToken = new CancelToken((cancel) => {
        // CancelStore._axiosPromiseCancel.push(cancel);
        / /});
    
    
        if (store.getters.token) {
        // Make each request carry a custom signature
            config.headers['Authorization'] = 'xxx' + store.getters.token;
        }
        return config;
    },
    error= > {
        MessageBox(error);
        return Promise.reject(error); });Copy the code

Step 4: Set up the Response interceptor

service.interceptors.response.use(
    (response) = > {
        const res = response.data;
        if (res.code === 200) {
            return response.data;
        } else if (res.code === 407) {
            console.log("Token invalid, jump to login page");
        } else {
            Message({
                masssage: res.message,
                type: error,
            });
            return Promise.reject("error"); }},error= > {
        console.log(error);
        Message({
            message: error.message,
            type: 'error'
        })
        return Promise.reject(error)
    }
);
Copy the code

Step 5: Expose yourself

export default service
Copy the code

How do I cancel one or more requests

import axios from 'axios';
window.axiosCancel = [];  // Define an identifier to store cancellation requests
service.interceptors.request.use(config= > {
    return config
    config.cancelToken = new axios.CancelToken(cancel= > {
        window.axiosCancel.push({
            cancel
        })
    })
});
// Return data interception after request
service.interceptors.response.use(res= >{},(res) = > {
    return Promise.reject(res)
})
Copy the code

Used in a component to cancel all pending requests before sending a new request

Methods: {cancel(){ // Set a function to be executed before the request is executed
        // Get the cache request cancel id array, cancel all associated requests
        let cancelArr = window.axiosCancel;
        cancelArr.forEach((ele, index) = > {
            ele.cancel("Request cancelled.") // Return this custom error message in the failed function
            delete window.axiosCancel[index]
        })
    },
    getList(){
        this.cancel()   // Cancel all requests that are being sent
        axios.post(..)  // Send a new request}}Copy the code

If we don’t want to define a cancel function in each component, we can mount this function on the prototype of the Vue instance so that we can use cancel in any component:this.cancel()As shown in the followingmain.jsIn the file:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'/ / into the store
Vue.config.productionTip = false
 
// Mount cancel to vue prototype
Vue.prototype.cancel = function(){
    // Get the cache request cancel id array, cancel all associated requests
    let cancelArr = window.axiosCancel;
    cancelArr = cancelArr || [];
    cancelArr.forEach((ele, index) = > {
        ele.cancel("Request cancelled.")  // Return this custom error message in the failed function
        delete window.axiosCancel[index]
    })
}
 
window.vm=new Vue({
  el: '#app'.data(){
    return{
    }
  },
  router,
  store,
  components: { App },
})
Copy the code

Alternatively, if we wanted to cancel all requests from the previous page every time a route page jumps, we could put the contents of cancel() in a route interceptor,router/index.jsFile configuration, as follows:

// Import route and vUE
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
 
// Create a routing instance
const router = new Router({
  linkActiveClass: 'app-active'.// Route color when selected (app-active is a custom class style class)
  routes: [{/ / root path
	path: '/'.redirect: '/home'.component: () = > import('@/pages/home')  // Route lazy loading
    },
    {
	path: '/home'.name: 'home'.component: () = > import('@/pages/home'),}})/* Route interceptor before route jump */
router.beforeEach((to, from, next) = > {
    // Get the cache request cancel id array, cancel all associated requests
    let cancelArr = window.axiosCancel;
    cancelArr.forEach((ele, index) = > {
        ele.cancel("Request cancelled.")  // Return this custom error message in the failed function
        delete window.axiosCancel[index]
    })
    next()
})
/* Route interceptor route jump after operation */
router.afterEach(to= >{})// Export the route for external reception, mainly for main.js reception
export default router
Copy the code