美文网首页
axios取消请求以及获取文件上传进度

axios取消请求以及获取文件上传进度

作者: 浅忆_0810 | 来源:发表于2021-03-27 11:07 被阅读0次

1. axios取消接口请求

  1. 通过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.');
    
  2. 通过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;
  })
})

相关文章

网友评论

      本文标题:axios取消请求以及获取文件上传进度

      本文链接:https://www.haomeiwen.com/subject/zdwehltx.html