头图
In daily front-end development, frequent repeated requests are often encountered, which will cause unnecessary pressure on the server and the network, which can be solved by canceling repeated requests.

Scenes

  • Order data condition filter query
  • Form submit button is frequently clicked
  • Routing page switching request is not canceled

solution

When each request is initiated, the currently stored tags are stored in an array or Map. For each request, the request interception is queried for repetition. If it is repeated, the repeated request in the history is cancelled, and the current request is initiated again. If there are no duplicates, add a storage tag and request as normal, clear storage tags for completed requests

How to cancel a request in axios

  1. A cancel token can be created using the CancelToken.source factory method, like this:
 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 {
     // 处理错误
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
  1. Cancel tokens can also be created by passing an executor function to the CancelToken constructor:
 const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});

// cancel the request
cancel();

Packaged and used in the project

Basic variable definition

 // 是否取消重复请求开关
const cancelDuplicated = true

// 存储每个请求中的map
const pendingXHRMap = new Map()

// 取消请求类型定义 便于后期对此类型不做异常处理
const REQUEST_TYPE = {
  DUPLICATED_REQUEST: 'duplicatedRequest'
}

Function to set duplicate flags

 const duplicatedKeyFn = (config) => {
  // 可在此设置用户自定义其他唯一标识 默认按请求方式 + 请求地址
  return `${config.method}${config.url}`
}

add to request log

 const addPendingXHR = (config) => {
  if (!cancelDuplicated) {
    return
  }
  const duplicatedKey = JSON.stringify({
    duplicatedKey: duplicatedKeyFn(config),
    type: REQUEST_TYPE.DUPLICATED_REQUEST
  })
  config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
    if (duplicatedKey && !pendingXHRMap.has(duplicatedKey)) {
      pendingXHRMap.set(duplicatedKey, cancel)
    }
  })
}

delete request record

 const removePendingXHR = (config) => {
  if (!cancelDuplicated) {
    return
  }
  const duplicatedKey = JSON.stringify({
    duplicatedKey: duplicatedKeyFn(config),
    type: REQUEST_TYPE.DUPLICATED_REQUEST
  })
  if (duplicatedKey && pendingXHRMap.has(duplicatedKey)) {
    const cancel = pendingXHRMap.get(duplicatedKey)
    cancel(duplicatedKey)
    pendingXHRMap.delete(duplicatedKey)
  }
}

used in axios

 // 请求拦截处理
axios.interceptors.request.use(config => {
    removePendingXHR(config)
    addPendingXHR(config)
    ...
    return config
})

// 响应拦截处理
axios.interceptors.response.use(response => {
    removePendingXHR(response.config)
    ...
}, error => {
    // 如果是取消请求类型则忽略异常处理
    let isDuplicatedType;
    try {
      const errorType = (JSON.parse(error.message) || {}).type
      isDuplicatedType = errorType === REQUEST_TYPE.DUPLICATED_REQUEST;
    } catch (error) {
      isDuplicatedType = false
    }
    if (!isDuplicatedType) {
        // 其他异常处理
    }
})

In Vue, when the route switches pages, all requests to the previous page are canceled

 router.beforeEach((to, from, next) => {
    // 遍历pendingMap,将上一个页面的所有请求cancel掉
    pendingXHRMap.forEach((cancel) => {
        cancel();
    });
    pendingXHRMap.clear()
})

Summarize

This article mainly introduces the repeated requests that are frequently initiated in various situations in the daily front-end development, which will cause unnecessary pressure on the server and the network, which can be solved by canceling the repeated requests.

Focus on front-end development, share dry goods related to front-end technology, public account: Nancheng Front-end (ID: nanchengfe)

refer to

axios official website cancellation request

How to gracefully solve the "duplicate request" problem


南城FE
2.2k 声望577 粉丝