javascript 无法通过CancelToken取消Axios发布请求

icomxhvb  于 2022-12-28  发布在  Java
关注(0)|答案(5)|浏览(221)

此代码取消GET请求,但不能中止POST调用。
如果我先发送GET请求,并且我没有通过abortAll方法取消它们,它们只是自己完成这个令牌,自己取消,并且不处理下一个请求?我错过了什么?谢谢,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();

}

}
c6ubokkw

c6ubokkw1#

我发现你可以用这种方式取消POST请求,我误解了这个文档部分。在前面的代码中,我把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()
kadbb459

kadbb4592#

使用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;
 })
 .catch((error)=>{
     return error;
 });
prdp8dxp

prdp8dxp3#

使用内部组件DidMount生命周期挂钩:

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
}
}, [])

注:对于POST请求,请将cancelToken作为第3个参数传递

Axios.post(`endpointURL`, {data}, {
 cancelToken: ourRequest.token, // 2nd step
})
s6fujrry

s6fujrry4#

也许我错了,但是每个请求应该有一个唯一的源对象。

c90pui9n

c90pui9n5#

使用ReactJs的最简单实施

import axios from 'axios';

class MyComponent extends Component {
  constructor (props) {
    super(props)

    this.state = {
      data: []
    }
  }

  componentDidMount () {
    this.axiosCancelSource = axios.CancelToken.source()

    axios
      .get('data.json', { cancelToken: this.axiosCancelSource.token })
      .then(response => {
        this.setState({
          data: response.data.posts
        })
      })
      .catch(err => console.log(err))
  }

  componentWillUnmount () {
    console.log('unmount component')
    this.axiosCancelSource.cancel('Component unmounted.')
  }

  render () {
    const { data } = this.state

    return (
     <div>
          {data.items.map((item, i) => {
            return <div>{item.name}</div>
          })}
      </div>
    )
  }
}

相关问题