使用 XMLHttpRequest (XHR) 中断请求
实现方式:
1. 创建一个 XHR 对象。
2. 发起请求后,根据需要调用 abort() 方法即可终止请求。
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data', true);
// 监听请求状态
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('请求成功:', xhr.responseText);
}
};
// 发送请求
xhr.send();
// 在某个时刻中断请求
setTimeout(() => {
xhr.abort(); // 中断请求
console.log('请求已被中断');
}, 1000);
使用 Axios 的取消功能
实现方式:
1. 创建一个 CancelToken 实例,传递给请求配置。
2. 调用 cancel 方法中断请求。
const axios = require('axios');
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 发起请求
axios.get('https://example.com/data', { cancelToken: source.token })
.then(response => console.log('请求成功:', response.data))
.catch(err => {
if (axios.isCancel(err)) {
console.log('请求被中断:', err.message);
} else {
console.error('请求失败:', err);
}
});
// 中断请求
setTimeout(() => {
source.cancel('操作已取消');
}, 1000);
使用 Fetch API 的 AbortController
实现方法:
1. 创建一个 AbortController 对象。
2. 将其关联的 signal 属性传递给 Fetch 的 init 参数。
3. 调用 AbortController 的 abort() 方法即可中断请求。
const controller = new AbortController();
const signal = controller.signal;
// 发起请求
fetch('https://example.com/data', { signal })
.then(response => response.json())
.then(data => console.log('请求成功:', data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('请求被中断');
} else {
console.error('请求失败:', err);
}
});
// 在某个时刻中断请求
setTimeout(() => {
controller.abort();
console.log('Fetch 请求已中断');
}, 2000);
总结
方式 | 优点 |
---|---|
XHR | 简单、支持早期浏览器 |
Axios | 功能丰富,封装性强 |
Fetch + Abort | 语法现代化,灵活性高 |