1. 程式人生 > 其它 >axios取消請求的實現

axios取消請求的實現

單個介面取消

通過傳遞一個 executor 函式到 CancelToken 的建構函式來建立一個 cancel token
interface.js

import axios from 'axios'

export function getXXX(data, that = {}, cancelFuncName = 'cancel') {
  return request({
    timeout: 6000,
    url: '/xxxx',
    method: 'post',
    data,
    cancelToken: new axios.CancelToken(function executor(c) {
      that[cancelFuncName] = c
    }),
  })
}

多個介面同時取消

使用 CancelToken.source 工廠方法建立一個 cancel token,藉助vuex和vue-router處理頁面跳轉的介面
interface.js


import axios from 'axios'
// 初始化取消請求物件
const CancelToken = axios.CancelToken
const source = CancelToken.source()

export function getXXX(data) {
  return request({
    url: '/xxx,
    method: 'post',
    data,
    cancelToken: source.token,
  })
}

store.js

import Vuex from 'vuex'

const store = new Vuex.Store({
  state: {
    source: {
      token: null,
      cancel: null,
    },
  },
})

export default store

router.js

import router from './router'
import axios from 'axios'
import store from './store'
router.beforeEach(async(to, from, next) => {
        const CancelToken = axios.CancelToken
        store.state.source.cancel && store.state.source.cancel()
        store.state.source = CancelToken.source()
        next()
})

request.js

import store from '@/store'
import axios from 'axios'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
})

service.interceptors.request.use(config => {
    // 初始化axios中的cancelToken 
    config.cancelToken = store.source.token
    return config
}, err => {
    return Promise.reject(err)
})

封裝CancelToken


import axios from 'axios'

export default class CancelToken {
  // 宣告一個 Map 用於儲存每個請求的標識 和 取消函式
  static pending = new Map()
  // 白名單, 寫入介面名稱
  static whiteRequest = []

  /**
   * 得到該格式的url
   * @param {AxiosRequestConfig} config
   * @returns
  */
  static getUrl(config) {
    return [config.method, config.url].join('&')
  }

  /**
   * 新增請求
   * @param {AxiosRequestConfig} config
  */
  static addPending(config) {
    const url = this.getUrl(config)
    config.cancelToken = new axios.CancelToken(cancel => {
      if (!this.pending.has(url)) { // 如果 pending 中不存在當前請求,則新增進去
        this.pending.set(url, cancel)
      }
    })
  }

  /**
   * 移除請求
   * @param {AxiosRequestConfig} config
  */
  static removePending(config) {
    const url = this.getUrl(config)
    const method = url.split('&')[1]
    console.log(method)
    if (this.pending.has(url) && !this.whiteRequest.includes(method)) { // 如果在 pending 中存在當前請求標識,需要取消當前請求,並且移除
      const cancel = this.pending.get(url)
      cancel(url)
      this.pending.delete(url)
    }
  }
  /**
   * 清空 pending 中的請求(在路由跳轉時呼叫)
  */
  static clearPending() {
    for (const [url, cancel] of this.pending) {
      cancel(url)
    }
    this.pending.clear()
  }
}

用法:


service.interceptors.request.use(
  config => {
    // 這裡的判斷用於處理白名單不參與取消請求
    if (!CancelToken.whiteRequest.includes(`${config.url}`)) {
      // 請求開始前,檢查一下是否已經有該請求了,有則取消掉該請求
      CancelToken.removePending(config)
      // 把當前請求新增進去
      CancelToken.addPending(config)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  },
)

instance.interceptors.response.use((resp: AxiosResponse<IResponse>) => {
  // 介面響應之後把這次請求清除
  CancelToken.removePending(resp.config)
  if(resp.data.status === 200) {
    // 介面請求成功
    return resp.data.data
  }
  return Promise.reject('')
})

router.beforeEach((to, from, next) => {
  // 路由跳轉要清除之前所有的請求快取
  CancelToken.clearPending()
  next()
})

https://www.jianshu.com/p/761114cbba68 詳情