无法通过CancelToken取消Axios发布请求 [英] Cant cancel Axios post request via CancelToken

查看:908
本文介绍了无法通过CancelToken取消Axios发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码取消GET请求,但无法中止POST调用。

如果我先发送GET请求而我不通过 abortAll 方法取消它们,只是自己完成这个令牌本身取消并且对下一个请求不起作用?
我缺少什么?
谢谢,约翰

This code cancel GET requests but cant abort POST calls.
If i send GET requests first and i dont cancel them via abortAll method,they just finish by themselves this token cancel by itself and doesnt work on next requests? What am i missing? Thanks,John

import axios from 'axios'
class RequestHandler {

 constructor(){
  this.cancelToken = axios.CancelToken;
  this.source = this.cancelToken.source();
 }

 get(url,callback){

  axios.get(url,{
   cancelToken:this.source.token,
  }).then(function(response){

        callback(response.data);

    }).catch(function(err){

        console.log(err);

    })

 }

post(url,callbackOnSuccess,callbackOnFail){
 axios.post(url,{

        cancelToken:this.source.token,

    }).then(function(response){

        callbackOnSuccess(response.data);

    }).catch(function(err){

        callbackOnFail()

    })
}

abortAll(){

 this.source.cancel();
    // regenerate cancelToken
 this.source = this.cancelToken.source();

}

}


推荐答案

我发现你可以通过这种方式取消发帖请求,我很想知道这个文档部分
在之前的代码中,我已将cancelToken传递给POST数据请求,而不是作为axios设置。

I have found out that you can cancel post request this way,i missunderstand this documentation part. In previous code,i have passed cancelToken to the POST data request not as a axios setting.

import axios from 'axios'


var CancelToken = axios.CancelToken;
var cancel;

axios({
  method: 'post',
  url: '/test',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  cancelToken: new CancelToken(function executor(c) {
      // An executor function receives a cancel function as a parameter
      cancel = c;
    })
}).then(()=>console.log('success')).catch(function(err){

  if(axios.isCancel(err)){

    console.log('im canceled');

  }
  else{

    console.log('im server response error');

  }

});
// this cancel the request
cancel()

这篇关于无法通过CancelToken取消Axios发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆