Vue axios interceptor commonly used repeated request cancellation

Vue axios interceptor commonly used repeated request cancellation

introduction

The previous article introduced the simple encapsulation of axios and the application scenarios and methods of axios interceptors. Today, let’s see how the interceptor handles situations where the response time is too long and the number of requests is too high.

How to cancel a request

Axios uses the internally provided CancelToken to cancel the request

Official website example 1: Use the CancelToken.source factory method to create a cancel token, like this

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // Handle error }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// Cancel the request (message parameter is optional)
source.cancel('Operation canceled by the user.');

Official website example 2: Create a cancel token by passing an executor function to the CancelToken constructor:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // The executor function receives a cancel function as a parameter cancel = c;
  })
});

// cancel the request
cancel();

You can see that the cancel tokens above are all created in a single request. In actual work, we need to process all requests. Next, let's see how to implement the function of canceling requests in the interceptor

Canceling duplicate requests in the interceptor

import axios from 'axios'
import baseURL from './config'
import qs from 'qs'

const pendingRequest = new Map(); // Request object const CancelToken = axios.CancelToken;

axios.defaults.timeout = 30000
axios.defaults.baseURL = baseURL.target

// Add request interceptor axios.interceptors.request.use(function(config) {
  // Do something before sending the request config.headers = {
      'content-type': 'application/json',
      'token': getToken()
  }
  // Get the request key
  let requestKey = getReqKey(config);

  // Determine whether it is a repeated request if (pendingRequest.has(requestKey)) { // It is a repeated request removeReqKey(requestKey); // Cancel }else{
    // Set cancelToken
    config.cancelToken = new CancelToken(function executor(cancel) {
      pendingRequest.set(requestKey, cancel); // set })
  }

  return config;
}, function (error) {
  // Request error return Promise.reject(error);
});

// Add response interceptor axios.interceptors.response.use(function (response) {
  // Delete requestKey in the request object
  let requestKey = getReqKey(response.config);
  removeReqKey(requestKey);

  // Do something with the returned data, such as intercepting the status if (response.data.status !== 200) {
      Toast({
        message: response.data.message,
        type: 'warning',
        duration: 1000
      })
      return
    }
    
  // No problem, return the server data return response.data;
}, function (error) {
  let requestKey = getReqKey(error.config);
  removeReqKey(requestKey);
  
  // Response error return Promise.reject(error);
});

// Get the request key
function getReqKey(config) {
  // The string generated by the request method, request address, and request parameters is used as the basis for whether to repeat the request const { method, url, params, data } = config; // Deconstruct these parameters // GET ---> params POST ---> data
  const requestKey = [method, url, qs.stringify(params), qs.stringify(data)].join('&');
  return requestKey;
}

// Cancel duplicate request function removeReqKey(key) {
  const cancelToken = pendingRequest.get(key);
  cancelToken(key); // Cancel the previously sent request pendingRequest.delete(key); // Delete requestKey in the request object
}

Conclusion

The above is the processing of repeated requests. If you are not clear about the interceptor, you can read the previous article. If you have any questions, you are welcome to correct me. I will update it as soon as possible.

This is the end of this article about the common repeated request cancellation of vue axios interceptor. For more related content about repeated request cancellation of axios interceptor, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

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
  • Detailed explanation of the configuration method of Vue request interceptor

<<:  MySQL 8.0.20 Window10 free installation version configuration and Navicat management tutorial graphic detailed explanation

>>:  Alibaba Cloud ECS Server Getting Started Process (Must-Read Tutorial for Newbies)

Recommend

base target="" controls the link's target open frame

<base target=_blank> changes the target fram...

Summary of situations where MySQL indexes will not be used

Types of Indexes in MySQL Generally, they can be ...

Summary of Common Problems with Mysql Indexes

Q1: What indexes does the database have? What are...

The most detailed method to install docker on CentOS 8

Install Docker on CentOS 8 Official documentation...

Detailed tutorial on how to monitor Nginx/Tomcat/MySQL using Zabbix

Table of contents Zabbix monitors Nginx Zabbix mo...

W3C Tutorial (3): W3C HTML Activities

HTML is a hybrid language used for publishing on ...

Detailed process of installing logstash in Docker

Edit docker-compose.yml and add the following con...

Example of implementing element table row and column dragging

The element ui table does not have a built-in dra...

How to obtain root permissions in a docker container

First, your container must be running You can vie...

MySQL 5.7.18 Archive compressed version installation tutorial

This article shares the specific method of instal...

Detailed steps for installing and configuring MySQL 5.7

1. Download MySQL 1. Log in to the official websi...