前端中断请求的常见方式

使用 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语法现代化,灵活性高
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值