axios 取消请求

本文详细介绍了axios中如何取消请求的流程,包括配置cancelToken、缓存cancel函数、在特定时机取消请求以及在错误回调中处理取消请求的情况。通过代码示例展示了在Vue客户端和服务端Koa的实现,并指出服务端延迟处理需使用Promise包裹setTimeout。同时,指出了取消请求只能在已发送且未返回结果时触发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(一)基本流程

1. 配置 cancelToken 对象

2. 缓存用于取消请求的 cancel 函数

3. 在后面特定的时机调用 cancel 函数取消请求

4. 在后面的回调中判断 如果 error 是cancel 做出相应处理

(二) 代码实现

客户端 vue:

<template>
  <div>
    <button @click="sendAjax">send</button>
    <button @click="canelSendBtn">cancel</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      cancelAjax: null
    }
  },
  methods: {
    // 发送
    sendAjax () {
      axios({
        url: '/getData',
        method: 'get',
        // 定义cancelToken参数,new一个axios.CancelToken实例,向该实例中传入执行器函数
        // c 是用于取消当前请求的函数
        // 将来取消请求时调用 cancel()
        cancelToken: new axios.CancelToken((c) => {
          this.cancelAjax = c
        })
      }).then((res) => {
        // 取消函数设置为 null 如果请求成功了 就不能取消了
        this.cancelAjax = null
        console.log('res', res.data)
      }).catch((err) => {
        this.cancelAjax = null
        console.log(err)
      })
    },
    canelSendBtn () {
      // 如果 cancelAjax 是一个函数 说明请求已发送 可以调用
      // 如果点击取消 则默认接口请求失败
      // 失败 error 就是 cancel 函数传的参数
      if (typeof this.cancelAjax === 'function') {
        this.cancelAjax('取消请求') // 
      } else {
        console.log('没有可取消的请求')
      }
    }
  }
}
</script>

<style>

</style>

服务端 koa

const koa = require('koa')
const router = require('koa-router')
const app = new koa()
const Router = new router()

app.use(Router.routes())

Router.get('/getData', async (ctx, next) => {
  await responseData()
  ctx.body = {
    code: 0,
    message: 'success'
  }
})

async function responseData () {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve()
    }, 2000)
  })
}

app.listen(3000, () => {
  console.log('server is running at 3000')
})

注意服务端 延迟 的实现。直接 setTimeout 是可以的,必须用Promise包一下

结果:

发送后点击取消,接口状态时 canceled

控制台打印 error

(三)区分取消请求error和请求error

.catch((err) => {
        this.cancelAjax = null
        if (axios.isCancel(err)) {
          console.log('取消请求error', err)
        } else {
          console.log(err)
        }
      })

(四)总结

取消可以触发的条件:请求已发送并且没有返回结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值