0%

单页应用路由切换接口问题

页面跳转的时候,处于异步请求的接口会自动被去取消掉,但是单页应用没有这种机制。我们需要手动实现。
axios是基于Promise的。本身对外暴露了一个 cancelToken的配置项用于取消,实际开发中需要在路由跳转的钩子中使用。

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

axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});

axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

底层实现主要依靠

xhr abort
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/abort

AbortControllerfetch
https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController

欢迎关注我的其它发布渠道

来发评论吧~
Powered By Valine
v1.5.2