axios cancel token

axios cancel request

单个请求

通过CancelToken.source工厂函数创建 cancel token

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 {
// handle error
}
});

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

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

通过执行函数创建 cancel token

1
2
3
4
5
6
7
8
9
10
11
12
const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});

// cancel the request
cancel();

在路由切换时 cancel request

配置全局变量 source

1
2
3
4
5
6
Vue.prototype.store = {
source: {
token: null,
cancel: null
}
};

配置 router

1
2
3
4
5
6
7
8
9
//router.js

router.beforeEach((to, from, next) => {
console.log(Vue.prototype.store.source);
const CancelToken = axios.CancelToken;
Vue.prototype.store.source.cancel && Vue.prototype.store.source.cancel();
Vue.prototype.store.source = CancelToken.source();
next();
});

配置 axios

1
2
3
4
5
6
7
const http = axios.create()
http.interceptors.request.use(config => {
config.cancelToken = store.source.token
return config
}, err => {
return Promise.reject(err)
})