1. axios
取消接口请求
-
通过
axios.CancelToken.source
生成取消令牌token
和取消方法cancel
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.post('/user/12345', params, { cancelToken: source.token }); // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.');
-
通过
axios.CancelToken
构造函数生成取消函数(推荐)const CancelToken = axios.CancelToken; let cancel; axios.post('/user/12345', params, { cancelToken: new CancelToken(function executor(c) { cancel = c; }) }); cancel();
2. 获取文件上传进度
const that = this;
axios.post('upload', params, {
onUploadProgress: (progressEvent) => {
/*
progressEvent.loaded 已上传文件大小
progressEvent.total 被上传文件的总大小
*/
const progressPrecent = (progressEvent.loaded / progressEvent.total * 100);
// 如果 token 失效,则取消该请求
if (!sessionStorage.getItem('token')) {
this.caccel();
}
},
cancelToken: new CancelToken(function executor(c) {
that.cancel = c;
})
})
网友评论