A brief discussion on Axios's solution to remove duplicate requests

A brief discussion on Axios's solution to remove duplicate requests

This solution has two main functions

1. After the request is sent, subsequent repeated requests will be cancelled and not processed, waiting for the first request to complete.
2. After the route jumps, all unfinished requests on the previous page are cleared.

1. Cancel duplicate requests

Prerequisites:

1. For the cancellation method officially provided by axios, please refer to the relevant documents: CancelToken
2.js Map related concepts
3. Secure query string parsing and string decomposition library qs, similar to JSON built into js

To simplify parameter processing, this solution only considers post requests, that is, if the method, url and data are the same, it is considered a duplicate request.

// axios.js
const pending = new Map()
/**
 * Add request * @param {Object} config
 **/
const addPending = (config) => {
  const url = [
    config.method,
    config.url,
    qs.stringify(config.data)
  ].join('&')
  if (pending.has(url)) { // If there is a current request in pending, cancel the subsequent request config.cancelToken = new axios.CancelToken(cancel => cancel(`Duplicate requests are actively intercepted: ${url}`))
  } else { // If the current request does not exist in pending, add it config.cancelToken = config.cancelToken || new axios.CancelToken(cancel => {
      pending.set(url, cancel)
    })
  }
}
/**
 * Remove request * @param {Object} config
 */
const removePending = (config) => {
  const url = [
    config.method,
    config.url.replace(config.baseURL, ''), // The response url will add the domain name, which needs to be removed to be consistent with the request URL qs.stringify(JSON.parse(config.data)) // Need to be consistent with the request parameter structure, the request is an object, and the response is a string].join('&')
  if (pending.has(url)) { // If the current request identifier exists in pending, cancel the current request and remove pending.delete(url)
  }
}

/* axios global request parameter settings, request interceptor*/
axios.interceptors.request.use(
  config => {
    addPending(config) // Add the current request to pending return config
  },
  error => {
    return Promise.reject(error)
  }
)
// Response interceptor is exception handling axios.interceptors.response.use(
  response => {
    removePending(response.config) // After the request is completed, remove the return response of this request
  },
  err => {
    if (err && err.config) {
      removePending(err.config) // After the request is completed, remove this request}
    return Promise.resolve(err.response)
  }
)

2. Clean up all requests

// axios.js
/**
 * Clear pending requests (called when routing redirects)
 */
export const clearPending = () => {
  for (const [url, cancel] of pending) {
    cancel(url)
  }
  pending.clear()
}
// router.js
router.beforeEach((to, from, next) => {
  // Route jump, clear all requests clearPending()
  })

This is the end of this article about Axios deduplication request solution. For more information about Axios deduplication request solution, please search for 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:
  • How to use axios to filter multiple repeated requests in a project
  • Axios cancel request and avoid duplicate requests
  • Axios cancels repeated requests
  • How to cancel repeated and useless requests in axios
  • Vue axios repeated click cancel the last request encapsulation method

<<:  How to use Nginx to prevent IP addresses from being maliciously resolved

>>:  Detailed explanation of viewing and setting SQL Mode in MySQL

Recommend

How to create a view on multiple tables in MySQL

In MySQL, create a view on two or more base table...

CSS3 achieves cool sliced ​​image carousel effect

Today we will learn how to use CSS to create a co...

MySQL 5.7.17 installation and configuration graphic tutorial

The blogger said : I have been writing a series o...

Install Percona Server+MySQL on CentOS 7

1. Environmental Description (1) CentOS-7-x86_64,...

Thirty HTML coding guidelines for beginners

1. Always close HTML tags In the source code of p...

Detailed steps for configuring virtual hosts in nginx

Virtual hosts use special software and hardware t...

How to use CSS3 to implement a queue animation similar to online live broadcast

A friend in the group asked a question before, th...

Summary of the use of Datetime and Timestamp in MySQL

Table of contents 1. How to represent the current...

Nginx dynamically forwards to upstream according to the path in the URL

In Nginx, there are some advanced scenarios where...

Tomcat class loader implementation method and example code

Tomcat defines multiple ClassLoaders internally s...