无法通过 CancelToken 取消 Axios 发布请求 [英] Cant cancel Axios post request via CancelToken
本文介绍了无法通过 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();
}
}
推荐答案
我发现你可以通过这种方式取消 post request,我不明白 本文档部分.在之前的代码中,我已将 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屋!
查看全文