此代码取消GET请求但不能中止POST调用.
如果我首先发送GET请求并且我不通过abortAll方法取消它们,他们只是自己完成这个令牌自己取消并且不能在下一个请求中工作?我错过了什么?谢谢,约翰
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Amo*_*gar 12
使用 cancelToken 和 source 取消对新请求的先前 Axios 请求。
https://github.com/axios/axios#cancellation
// cancelToken and source declaration
const CancelToken = axios.CancelToken;
let source = CancelToken.source();
source && source.cancel('Operation canceled due to new request.');
// save the new request for cancellation
source = axios.CancelToken.source();
axios.post(url, postData, {
cancelToken: source.token
})
.then((response)=>{
return response && response.data.payload);
})
.catch((error)=>{
return error;
});
Run Code Online (Sandbox Code Playgroud)
我发现你可以通过这种方式取消发帖请求,我很想念这个文档部分.在之前的代码中,我已将cancelToken传递给POST数据请求,而不是作为axios设置.
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()
Run Code Online (Sandbox Code Playgroud)
使用内部的 componentDidMount 生命周期钩子:
useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step
const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
} catch (err) {
console.log('There was a problem or request was cancelled.')
}
}
fetchPost()
return () => {
ourRequest.cancel() // <-- 3rd step
}
}, [])
Run Code Online (Sandbox Code Playgroud)
注意:对于 POST 请求,传递 cancelToken 作为第三个参数
Axios.post(`endpointURL`, {data}, {
cancelToken: ourRequest.token, // 2nd step
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11095 次 |
| 最近记录: |