(一)基本流程
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)
}
})
(四)总结
取消可以触发的条件:请求已发送并且没有返回结果