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

A brief understanding of MySQL storage field type query efficiency

The search performance from fastest to slowest is...

Solve the compatibility issue between MySQL 8.0 driver and Alibaba Druid version

This article mainly introduces the solution to th...

Graphic tutorial on configuring log server in Linux

Preface This article mainly introduces the releva...

Use of Linux xargs command

1. Function: xargs can convert the data separated...

How to deploy DoNetCore to Alibaba Cloud with Nginx

Basic environment configuration Please purchase t...

Application of CSS3 animation effects in activity pages

background Before we know it, a busy year is comi...

How to prevent duplicate submission in jquery project

In new projects, axios can prevent duplicate subm...

Steps to export the fields and related attributes of MySQL tables

Need to export the fields and properties of the t...

Teach you how to use webpack to package and compile TypeScript code

TypeScript Bundling webpack integration Usually, ...

MySQL Quick Data Comparison Techniques

In MySQL operation and maintenance, a R&D col...

Mysql accidental deletion of data solution and kill statement principle

mysql accidentally deleted data Using the delete ...

Summary of the data storage structure of the nginx http module

Starting from this section, we will explain the i...

HTML table tag tutorial (3): width and height attributes WIDTH, HEIGHT

By default, the width and height of the table are...

CSS uses the autoflow attribute to achieve seat selection effect

1. Autoflow attribute, if the length and width of...