如何取消请求发送

速记

根据使用的发送网络请求的API不同,取消方式也不同

  • XMLHttpRequest -> XMLHttpRequest.abort()
  • fetch -> AbortController
  • axios -> 原理和fetch一致(CancelToken)

XHR 使用 xhr.abort()

1
2
3
4
5
6
const xhr = new XMLHttpRequest();
xhr.open('GET','https://test/api', true);
xhr.send();

// 取消发送请求
xhr.abort();

fetch 使用 AbortController

步骤如下:

  • 发送请求时使用一个single选项控制fetch请求
  • control.abort()用以取消请求发送
  • 取消请求发送之后会得到异常AbortError
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const controller = new AbortController();
const single = controller.single;

const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');

downloadBtn.addEventListener('click', fetchData);
abortBtn.addEventListener('click', function() {
controller.abort();
})

function fetchData() {
fetch(url, { signal }).then(function(res) {
// ...
}).catch(function(e){
console.log('Download error: ' + e.message)
})
}

Axios 使用 CancelToken

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get("/test/api", {
cancelToken: source.token,
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log("Request canceled", thrown.message);
} else {
// handle error
}
});

axios.post(
'/test/api', {
name: 'name',
}, {
cancelToken: source.token,
}
);

// cancel the request (the message parameter is optional)
source.cancel("Operation canceled by the user.");