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

Usage and difference of Js module packaging exports require import

Table of contents 1. Commonjs exports and require...

jQuery plugin to achieve image suspension

This article shares the specific code of the jQue...

The new version of Chrome browser settings allows cross-domain implementation

Preface Currently, the front-end solves cross-dom...

Example of how to install kong gateway in docker

1. Create a Docker network docker network create ...

Detailed explanation of MySQL deadlock and database and table sharding issues

Record the problem points of MySQL production. Bu...

Analysis of the advantages of path.join() in Node.js

You might be wondering why you should use the pat...

Docker uses the Prune command to clean up the none image

Table of contents The creation and confusion of n...

Upgrading Windows Server 2008R2 File Server to Windows Server 2016

The user organization has two Windows Server 2008...

WeChat applet realizes simple tab switching effect

This article shares the specific code for WeChat ...

Detailed explanation of CocosCreator project structure mechanism

Table of contents 1. Project folder structure 1. ...

The solution of html2canvas that pictures cannot be captured normally

question First, let me talk about the problem I e...

12 Javascript table controls (DataGrid) are sorted out

When the DataSource property of a DataGrid control...

Example of implementing translation effect (transfrom: translate) with CSS3

We use the translate parameter to achieve movemen...

The use of vue directive v-bind and points to note

Table of contents 1. v-bind: can bind some data t...

Detailed tutorial on installing Docker on Windows

Since my local MySQL version is relatively low, I...