离开页面取消请求
前言
上一篇文章我们处理了axios的重复请求问题axios重复请求,今天来说一下如何在离开某个页面的时候将正在发送的请求取消掉
开始
基于上一篇的axios封装,当我们在编写某个页面的请求的时候
import request from '@/request/index';
export const test2: any = async (data: any, onCancel: OnCancel) => {
const controller = new AbortController();
const requestPromise = request.post('/test', data, {
signal: controller.signal,
});
if (typeof onCancel === 'function') {
// 如果是一个函数,则直接调用传一个取消方法给 这个方法
// 所以只要传进来是方法,就会直接传一个参数并直接触发这个函数
// 那传过来的这个方法就会接收到一个参数(就是取消函数() => controller.abort())
// 在调用uploadFile就可以拿到这个参数
onCancel(() => controller.abort()) as any; // 调用 onCancel 时传入取消函数
}
return requestPromise;
};
上面是用在页面中的请求函数,new AbortController()是axios官网推荐的用法,具体请查看官网
使用
废话少说,直接上代码
<template>
<div>
<el-button @click="requestAxios2">发送请求2</el-button>
<el-button @click="requestAxios3">发送请求3</el-button>
</div>
</template>
<script setup lang="ts">
import { test2 } from '@/request/test/index';
const list: CancelFunction[] = [];
// 发送post请求
const requestAxios2 = async () => {
try {
const requestPromise = await test2(
{ page: 1, limit: 10 },
(oncancle: CancelFunction) => {
list.push(oncancle);
},
);
console.log(requestPromise);
} catch (error) {
console.error('Error in requestAxios2:', error);
}
};
const requestAxios3 = async () => {
try {
const requestPromise = await test2(
{ page: 1, limit: 100 },
(oncancle: CancelFunction) => {
list.push(oncancle);
},
);
console.log(requestPromise);
} catch (error) {
if (error === '取消请求') {
console.log('取消请求');
}
}
};
onBeforeUnmount(() => {
list.forEach((item: any) => {
item();
});
});
</script>
<style lang="scss" scoped></style>
当我们在调用函数的时候,传入一个回调函数,将这个回调函数的的值保存在一个list中,当离开页面的时候直接循环调用这个数组,并执行依次执行,就能实现当离开页面的时候取消正在发送的请求
展示结果
当我们离开之后页面会打印取消请求,截图可能不容易开出来,具体实现查看,不过后端代码没有在上面,这里放出来大家可以参考一下
后端:
// 使用express
const express = require("express");
const cors = require("cors");
const app = express();
const port = 8000;
// 设置跨域
// 安装cors
// 使用cors解决跨域
// 中间件,用于解析 JSON 请求体
app.use(express.json());
// 中间件,用于解析 URL 编码请求体
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const timeout = 3000;
app.get("/api/table/:id", (req, res) => {
setTimeout(() => {
res.send("结束,get");
}, timeout);
});
app.get("/api/table", (req, res) => {
// 获取请求参数
let { page, limit } = req.query;
setTimeout(() => {
res.send("结束,get");
}, timeout);
});
app.post("/api/table", (req, res) => {
// 获取请求参数
let { page, limit } = req.body;
setTimeout(() => {
res.send("结束,post");
}, timeout);
});
app.post("/test", (req, res) => {
// 获取post请求参数
// console.log(req.body, "req");
let { page, limit } = req.body;
setTimeout(() => {
res.send({
code: 200,
data: {
page,
limit,
},
});
}, timeout);
});
app.listen(port, () => {
console.log("\x1b[36m%s\x1b[0m", "{^_^} 启动成功了哦!");
});
总结
以上是实现离开页面取消正在发送的请求,当然也可以在发送请求添加到数组的时候,给每个取消函数绑定一个唯一id,当请求完成之后,从这个数组里面移出,这样离开页面的时候循环调用就不会有多余的函数,保证页面的进一步优化