欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 【前端】中断请求的方式

【前端】中断请求的方式

2024/10/24 21:22:20 来源:https://blog.csdn.net/cpsxn/article/details/141889496  浏览:    关键词:【前端】中断请求的方式

一 使用 Axios 和取消令牌

1.步骤:

  1. 初始化取消源,创建CancelToken
const source = axios.CancelToken.source();
  1. 传递cancelToken, 发起请求
axios.get('/api/data', {cancelToken: source.token
});
  1. 触发取消请求
source.cancel('操作被取消');
  1. 判断错误是否由于取消请求操作引起的
if (axios.isCancel(error)) {console.log('请求已被取消');
}

2.示例:

<template><button @click="fetchData">获取数据</button><button @click="cancelRequest">取消请求</button>
</template><script setup>
import axios from 'axios';
import { ref } from 'vue';// 1.1初始化取消源
const cancelSource = ref(null);
// 发起请求
function fetchData() {// 创建CancelTokencancelSource.value = axios.CancelToken.source();axios.get('https://example.com/api/data', {// 2.传递cancelToken, 发起请求cancelToken: cancelSource.value.token,}).then(response => {console.log('响应数据:', response.data);}).catch(error => {// 4.判断是否取消请求if (axios.isCancel(error)) {console.log('请求已取消');} else {console.error('请求失败:', error);}});
}
// 3.点击按钮触发取消请求
function cancelRequest() {if (cancelSource.value) {cancelSource.value.cancel('取消请求');}
}
</script>

注: 检查是否被取消
在请求的 catch 函数中,通过 axios.isCancel(error) 检查错误是否是由取消操作引起的。
这样就可以在 Vue 3 中手动中断一个请求,并且在取消请求时进行相应的处理。

二 使用 Fetch API 和 AbortController

1. AbortController

AbortController 是一种用于取消 Fetch API 请求的标准方法,也可以与 axios 结合使用来取消请求。

2.使用 AbortController 的基本步骤

// 1.创建 AbortController
const controller = new AbortController();
const signal = controller.signal;// 2.将信号传递给 fetch 请求
fetch('https://example.com/api/data', { signal }).then(response => response.json()).then(data => console.log(data)).catch(error => {if (error.name === 'AbortError') {console.log('请求已中断');} else {// 处理其他错误}});// 2.将信号传递给 axios 请求
axios.get('/api/data', {signal: signal
}).then(response => {// 处理响应
}).catch(error => {if (error.name === 'CanceledError') {console.log('请求被取消');} else {console.error('请求失败', error);}
});// 3.在某个时刻决定中断请求
controller.abort();

注: 确保 axios 版本支持 AbortController(建议使用最新版本)。
取消请求后,需要在 catch 中检查错误类型。

三 使用 abort()

abort() 方法用于取消正在进行的 AJAX 请求。
在这里插入图片描述

1. 使用XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data');
xhr.send();// 取消请求
xhr.abort();

2.使用jQuery.ajax

var jqXHR = $.ajax({url: '/api/data',type: 'GET'
});// 取消请求
jqXHR.abort();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com