It is common for projects to encounter scenarios that require active interface cancellation. Axios provides the function of CancelToken to actively stop the current request, thus avoiding invalid requests and optimizing network performance

Scenario: The remote search interface frequently requests data. If the second interface succeeds first, the data returned by the first interface is displayed

Import axios from 'axios' // Store pengding request container export const pendingList = new Map() // Generate each request identifier export const getFetchKey = (config) => { const { url, data, method } = config let token if (method === 'get') { token = [method, url].join('&') } else { token = [method, url, JSON.stringify(data)].join('&')} return token} // Add pengding request export const addPending = (config) => {const fetchKey = getFetchKey(config) if (fetchKey) { config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => { if (! pendingList.has(fetchKey)) { pendingList.set(fetchKey, Remove pengding request export const removePending = (config) => {const fetchKey = getFetchKey(config) if (fetchKey) {if (pendingList.has(fetchKey)) {pendingList.delete(fetchKey)}} // Cancel the request export const cancelPending = (config) => { const fetchKey = getFetchKey(config) if (fetchKey) { if (pendingList.has(fetchKey)) { const cancel = pendingList.get(fetchKey) cancel('cancel') pendingList.delete(fetchKey) } } }Copy the code

Axios interceptor configuration – Prevents frequent requests

  • Request to determine whether the request is repeated, if repeated to cancel the previous request
  • Adds the current request to a Pending container when requested
  • Removes the current request from the Pending container on success or failure
/** * axios interceptor configuration */ import {addPending, removePending, cancelPending, } the from '@ util/cancel - request import axios from' axios / / request interceptor axios. Interceptors. Request. Use request (= > {/ / Before sending a request, first check whether the request has been repeated. // Add the request to the pendingList. AddPending (Request) return Request}, Error = > {return Promise. The error (error)}) axios. Interceptors. Response. Use (response = > {/ / request successfully remove pengding state removePending(response) if (response.status === 200) { return Promise.resolve(response) } else { return Promise.reject(response) } }, Error => {// request failed to remove pengding state removePending(error.response) return promise.reject (error.response)})Copy the code