SoFunction
Updated on 2025-03-08

axios cancel requests and avoid duplicate requests

origin

A certain page requires the function of downloading all data, with a large amount of data download and a long interface delay...

The initial data loading of a certain page is extended for 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 search data...

These situations require us to:

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

status quo

The system is based on the secondary development of vue-element-admin, which is open sourced by Lao Ge Hua Pants. The request uses axios, and the encapsulated key code is as follows:

// create an axios instance
const service = ({
  baseURL: .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 of data    return ({
      ...data
    },
    // Conversion of arrays    { arrayFormat: 'brackets' })
  }]
})

// request interceptor
(
  config => {
    // do something before request is sent

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

Methods to initiate a request:

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

Cancel request cancelToken

Its official documentation:Cancel:

const CancelToken = ;
const source = ();

('/user/12345', {
  cancelToken: 
}).catch(function(thrown) {
  if ((thrown)) {
    ('Request canceled', );
  } else {
     // Handle errors  }
});

('/user/12345', {
  name: 'new name'
}, {
  cancelToken: 
})

// Cancel the request (the message parameter is optional)('Operation canceled by the user.');

Modified request method

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

When requesting, create a cameraToken:

// In component method = ()
remoreApi(data, ).then(....).catch(....).finally(....)

When the request needs to be cancelled, execute:

// In component method('Cancel download')

Avoid duplicate requests

Avoid repeated requests from one interface to avoid delayed interface return data overwriting the return data of another interface, causing data display errors. The idea is also relatively simple, using a global Map to store the request identifier and the corresponding cancelToken. Before initiating a request, the cancel method corresponding to the cancelToken is called according to the request identifier, and then a new request is issued to meet the conditions.

Summarize

This is the article about axios cancellation requests and avoiding duplicate requests. For more related axios cancellation requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!