axios取消请求

372 阅读1分钟

指定安装axios版本 npm install axios@0.21.0 --save

一、CancelToken

v0.22.0版本之前使用此方法可行

1、工厂创建取消令牌

发送请求的方法

handleSend() {
      const CancelToken = axios.CancelToken
      this.cancel = CancelToken.source()
        //get请求
       axios.get('/brand/getBrandList', {
        cancelToken: this.cancel.token
       }).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
           console.log('Request canceled', thrown.message)
         } else {
           // 处理错误
         }
       })
        //post请求
      axios.post('/brand/delete', {
        id: 177
      }, {
        cancelToken: this.cancel.token
      }).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message)
        } else {
          // 处理错误
        }
      })
    },

取消接口请求

      // 取消请求(message 参数是可选的)
      this.cancel.cancel('Operation canceled by the user.')

2、执行器函数传递给构造函数来创建取消令牌

发送请求方法

handleSend{
  const self = this
      var CancelToken = axios.CancelToken
      axios.get('/brand/getBrandList', {
        cancelToken: new CancelToken(function executor(c) {
          self.cancel = c
        })
      })
}

取消接口请求

    this.cancel()

二、AbortController

    const controller = new AbortController();
    axios.get('/foo/bar',{ 
        signal: controller.signal 
    }).then(function(response) { 
        //... 
    }); 
    // cancel the request
    controller.abort()