axios取消已经发送的请求

145 阅读1分钟

一、定义导出接口时,多传一个options

// 导出
export const exportApi = (url, data, options) => {
  return axios({
    url,
    method: 'post',
    responseType: 'blob',
    headers: { loading: false },
    data,
    ...options
  })
}

二、利用 CancelToken 构造函数,保存一个取消请求的函数(cancel)

import axios from 'axios'

// 定义一个取消请求的方法,初始值为null
let cancel = null

...

// 在调用导出接口时,传入 cancelToken
    setLoading(true)
    exportApi(exportUrl, exportParams, {
      cancelToken: new axios.CancelToken(c => (cancel = c))
    })
      .then(data => {
        const blob = new Blob([data])
        const objectURL = URL.createObjectURL(blob)
        let btn = document.createElement('a')
        btn.download = title
        btn.href = objectURL
        btn.click()
        URL.revokeObjectURL(objectURL)
        btn = null
        setPercent(99)
        message.success('下载成功')
        setLoading(false)
      })
      .catch(error => {
        console.log('导出接口出错', error)
        message.error('取消批量导出')
        setLoading(false)
      })


三、当点击【取消】按钮时,调用 cancel 方法

  const handleColse = () => {
    console.log('handleColse', cancel)
    onCancel()
    clearInterval(timer.current)
    if (cancel) {
      cancel('取消请求')
      cancel = null
    }
  }