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

Summary of some common uses of refs in React

Table of contents What are Refs 1. String type Re...

Zen coding for editplus example code description

For example, he enters: XML/HTML Code div#page>...

How to purchase and initially build a server

I haven't worked with servers for a while. No...

How to make a div height adaptive to the browser height

This old question has troubled countless front-end...

How to install mysql5.7.24 binary version on Centos 7 and how to solve it

MySQL binary installation method Download mysql h...

Solution to input cursor misalignment in Chrome, Firefox, and IE

Detailed explanation of the misplacement of the in...

Detailed analysis of when tomcat writes back the response datagram

The question arises This question arose when I wa...

Detailed explanation of scheduled tasks for ordinary users in Linux

Preface Ordinary users define crontab scheduled t...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

Steps to purchase a cloud server and install the Pagoda Panel on Alibaba Cloud

Alibaba Cloud purchases servers Purchase a cloud ...

Introduction to who command examples in Linux

About who Displays users logged into the system. ...