Axios cancel request and avoid duplicate requests

Axios cancel request and avoid duplicate requests

origin

A certain page needs to download all data, the amount of data to be downloaded is large, and the interface delay is long...

The initial data loading of a certain page takes a long time, but a single search is fast. When the initial data is loading, the search interface returns, and the subsequent return of the initial data covers the display of the searched data....

These situations require us to:

  • Ability to manually cancel/terminate a request.
  • Some page interfaces can only have one request at a time.

status quo

The system is a secondary development based on the open source vue-element-admin of Laoge Huakucha. The request uses axios, and the key code of the encapsulated request.js is as follows:

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000, // request timeout
  transformRequest: [function(data) {
    // Perform arbitrary conversion on data return Qs.stringify({
      ...data
    },
    // array conversion { arrayFormat: 'brackets' })
  }]
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

Method to initiate the request:

export function remoteApi(data) {
  return request({
    url: '/api',
    method: 'post',
    data
  })
}

Cancel request cancelToken

Its official documentation: Cancel:

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.');

Modified request method

export function remoteApi(data, cancelToken) {
  return request({
    url: '/api',
    method: 'post',
    cancelToken,
    data
  })
}

When making an actual request, create a cachelToken:

// In the component method this.cancelToken = CancelToken.source()
remoreApi(data, this.cancelToken).then(....).catch(....).finally(....)

To cancel a request, execute:

// In the component method this.cancelToken.cancel('Cancel download')

Avoid duplicate requests

Avoid repeated requests to an interface to prevent the return data of the interface with a longer delay from overwriting the return data of another interface, causing data display errors. The idea is relatively simple, using a global Map to store request identifiers and corresponding cancelTokens. Before initiating a request, call the cancel method of the corresponding cancelToken according to the request identifier, and then issue a new request to meet the conditions.

Summarize

This is the end of this article about canceling axios requests and avoiding duplicate requests. For more information about canceling axios requests, 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:
  • Axios global request parameter settings, request and return interceptor methods
  • Steps for Vue to encapsulate Axios requests and interceptors
  • Vue axios repeated click cancel the last request encapsulation method
  • How to cancel repeated and useless requests in axios
  • Axios cancels repeated requests
  • Vue axios interceptor commonly used repeated request cancellation

<<:  Detailed explanation of MLSQL compile-time permission control example

>>:  A brief analysis of vsftpd service configuration in Linux (anonymous, user, virtual user)

Recommend

How to hide the version number in Nginx

Nginx hides version number In a production enviro...

XHTML three document type declarations

XHTML defines three document type declarations. T...

MySQL export of entire or single table data

Export a single table mysqldump -u user -p dbname...

HTML displays ellipsis beyond the text... implemented through text-overflow

You need to apply CSS to div or span at the same t...

WeChat applet realizes the nine-square grid effect

This article shares the specific code for the WeC...

Command to remove (delete) symbolic link in Linux

You may sometimes need to create or delete symbol...

Practical record of optimizing MySQL tables with tens of millions of data

Preface Let me explain here first. Many people on...

Understand the principle of page replacement algorithm through code examples

Page replacement algorithm: The essence is to mak...

The whole process of configuring reverse proxy locally through nginx

Preface Nginx is a lightweight HTTP server that u...

Media query combined with rem layout in CSS3 to adapt to mobile screens

CSS3 syntax: (1rem = 100px for a 750px design) @m...

MySQL trigger usage scenarios and method examples

trigger: Trigger usage scenarios and correspondin...

Detailed explanation of DOM DIFF algorithm in react application

Table of contents Preface What is VirtualDOM? Rea...

Play with the connect function with timeout in Linux

In the previous article, we played with timeouts ...

A brief analysis of the use of the HTML webpack plugin

Using the html-webpack-plugin plug-in to start th...