Cant cancel Axios post request via CancelToken

后端 未结 5 1904
悲哀的现实
悲哀的现实 2020-12-10 16:04

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 themsel

相关标签:
5条回答
  • 2020-12-10 16:14

    Maybe I'm wrong, but each request should have a unique source object.

    0 讨论(0)
  • 2020-12-10 16:17

    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()
    
    0 讨论(0)
  • 2020-12-10 16:17

    Using inside componentDidMount lifecycle hook:

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

    Note: For POST request, pass cancelToken as 3rd argument

    Axios.post(`endpointURL`, {data}, {
     cancelToken: ourRequest.token, // 2nd step
    })
    
    0 讨论(0)
  • 2020-12-10 16:19

    Simplest implementation using 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>
        )
      }
    }
    
    0 讨论(0)
  • 2020-12-10 16:37

    Cancel previous Axios request on new request with cancelToken and source.

    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;
     });
    
    0 讨论(0)
提交回复
热议问题