Axios complete secondary packaging and use

    The encapsulation of network requests is essential in the front-end project. Recently, the encapsulation of the next project axios has been refactored and recorded.

    axios secondary packaging

    import axios from "axios";
    import router from "../router"; //See the modification of the routing file packaged by the specific project
    
    // Jump to login page
    const toLogin = () => {
      router. replace({
        path: "/login"
      });
    };
    
    //Encapsulate status code error handling function
    const errorHandle = status => {
      switch (status) {
        // Jump to the login page when the login is unsuccessful
        case 401:
          console.log("Authentication failed, no login or no permission");
          toLogin();
          break;
        case 403:
          //token has expired, clear the token storage
          localStorage. removeItem("token");
          console.log("token verification failed");
          toLogin();
          break;
        case 404:
          console.log("The requested resource does not exist");
          break;
        default:
          console.log("Request error, status code: " + status);
          break;
      }
    };
    
    
    // Axios secondary packaging
    const devBaseURL = "baseURL of the interface in the development environment";
    const proBaseURL = "baseURL of the interface in the production environment";
    //You can see the names of the development environment and production environment under the config folder of vue, usually development and production
    const baseURL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;
    
    //Create an axios instance
    const service = axios. create({
      baseURL: baseUrl,
      // configure timeout
      timeout: 2000
    });
    //Set the Content-Type of the post request, do you need to write the background specification
    service.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    //Allow cross-domain transfer of cookies with credentials, depending on the specific project, usually set to true
    service.defaults.withCredentials = true;
    
    //ES6 destructuring assignment, introducing cancelToken and isCancel
    const { CancelToken, isCancel } = axios;
    
    //Define a global variable to store different urls to avoid intercepting normal requests when there are multiple requests on the same page
      let pending = {};
    
    
    // Set the request interceptor of axios
    service.interceptors.request.use(config => {
      //Get the token in the local storage, if there is a token, add it to the request, the token is generally stored locally or in vuex
      let token = localStorage. getItem("token");
      token && (config. headers. Authorization = token);
    
      //Cancel repeated request
      //Use the url of each request as the uniquely identified key value to cancel repeated requests
     let key = config.url + "&" + config.method;
     //If the previous request already exists, call the function to cancel the last repeated request
     if (pending[key]) pending[key]("Cancel repeated request");
     config.cancelToken = new CancelToken((c) => {
     // Assign the function c of the cancellation request to pending[key] to save the cancellation function
      pending[key] = c;
     });
      //Remember to return to config to proceed with the next request
      return config;
    });
    
    
    //Set the response interceptor of axios
    service.interceptors.response.use(
      response => {
        //If successful, return the useful data in the response
        return response.data
      },
      // Unified error handling on failure
      error => {
        let { response } = error;
        //Determine whether there is an error due to repeated requests
        if (isCancel(error)) console.log("The request failed because of " + error.message);
        else if (response) {
          errorHandle(response. status);
        }
        //Determine whether the client is connected to the Internet
        if (!window.navigator.onLine) {
          //Internet disconnection processing: jump to the disconnection page/prompt for network errors, etc.
          alert("Please check if the network is connected");
        }
        //An error breaks the promise chain
        return new Promise(() => {});
      }
    );
    
    //Export the encapsulated aixos
    export default service;
    

    use

    Introduce the encapsulated service in the interface management file, here I still call it axios: import axios from 'the path of the encapsulated service';
    Make api requests in the interface management file. When there are many interfaces, pay attention to write the function of each interface to facilitate subsequent calls

    //1. Login
    export const login = data => axios.post("/user/login", data)//The path is filled in according to the interface document given by the background
    // 2. Change the password
    export const updatePwd = data => axios. put("/user/password", data)
    

    In the page use:
    Use import to import the interface to be used,

    import {login, updatePwd } from "@/api/index";
    login().then(res=>console.log(res))
    


    Principle of axios interceptor

    When we use the Axios instance to send a request, get, post and other methods are actually called Axios.prototype.request methods, and finally return a promise chain call, and the actual request occurs in dispatchRequest.

    When using an interceptor, axios calls request to create a chain array (chain=[dispatchReauest, undefined], undefined only acts as a placeholder, because subsequent chain executions will take two numbers each time) and put the request interceptor in In front of dispatchReauest, the response interceptor is placed behind undefined, and then the chain is traversed in order to execute, and two numbers are taken out each time, one is the successful function of the interceptor and the other is the failed function, which corresponds to the successful callback and failed callback of the incoming promise. Guaranteed the execution order of request interceptor-api request-response interceptor

    Note: The ones set after the request interceptor are executed first, and the ones set first by the response interceptor are executed first

    Implement interceptors using native AJAX:Still worrying about mastering Ajax? Read this article and you will find all the answers for Ajax

    Popular posts from this blog

    大学资料分享——广工计院各个科目实验报告、课设及期末复习资料!!

    JAVA Traffic Signal Light Course Design (Source Code + Report + Video Demonstration)

    Win10 远程计算机或设备将不接受连接