how to cancel/abort ajax request in axios

前端 未结 8 677
广开言路
广开言路 2020-12-05 06:19

I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline c

相关标签:
8条回答
  • 2020-12-05 06:38

    Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:

    Example: getting some comments from API:

    // declare an ajax request's cancelToken (globally)
    let ajaxRequest = null; 
    
    function getComments() {
    
        // cancel  previous ajax if exists
        if (ajaxRequest ) {
            ajaxRequest.cancel(); 
        }
    
        // creates a new token for upcomming ajax (overwrite the previous one)
        ajaxRequest = axios.CancelToken.source();  
    
        return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
            console.log(response.data)
        }).catch(function(err) {
            if (axios.isCancel(err)) {
               console.log('Previous request canceled, new request is send', err.message);
            } else {
                   // handle error
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-05 06:38

    There is really nice package with few examples of usage called axios-cancel. I've found it very helpful. Here is the link: https://www.npmjs.com/package/axios-cancel

    0 讨论(0)
  • 2020-12-05 06:43

    This is how I did it using promises in node. Pollings stop after making the first request.

     var axios = require('axios');
        var CancelToken = axios.CancelToken;
        var cancel;
        axios.get('www.url.com',
                          {
                            cancelToken: new CancelToken(
                                function executor(c) {
                                    cancel = c;
                                 })
                          }
                ).then((response) =>{            
                    cancel();               
                  })
    
    0 讨论(0)
  • 2020-12-05 06:46

    Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:

    1. Promise cancallation API (CPromise):

    Live browser example

     const cpAxios= require('cp-axios');
     const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
     
     const chain = cpAxios(url)
          .timeout(5000)
          .then(response=> {
              console.log(`Done: ${JSON.stringify(response.data)}`)
          }, err => {
              console.warn(`Request failed: ${err}`)
          });
     
     setTimeout(() => {
        chain.cancel();
     }, 500);
    

    2. Using AbortController signal API:

     const cpAxios= require('cp-axios');
     const CPromise= require('c-promise2');
     const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
     
     const abortController = new CPromise.AbortController();
     const {signal} = abortController;
     
     const chain = cpAxios(url, {signal})
          .timeout(5000)
          .then(response=> {
              console.log(`Done: ${JSON.stringify(response.data)}`)
          }, err => {
              console.warn(`Request failed: ${err}`)
          });
     
     setTimeout(() => {
        abortController.abort();
     }, 500);
    

    3. Using a plain axios cancelToken:

     const cpAxios= require('cp-axios');
     const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
    
     const source = cpAxios.CancelToken.source();
     
     cpAxios(url, {cancelToken: source.token})
          .timeout(5000)
          .then(response=> {
              console.log(`Done: ${JSON.stringify(response.data)}`)
          }, err => {
              console.warn(`Request failed: ${err}`)
          });
     
     setTimeout(() => {
        source.cancel();
     }, 500);
    
    0 讨论(0)
  • 2020-12-05 06:48

    Axios does not support canceling requests at the moment. Please see this issue for details.

    UPDATE: Cancellation support was added in axios v0.15.

    EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

    Example:

    const cancelTokenSource = axios.CancelToken.source();
    
    axios.get('/user/12345', {
      cancelToken: cancelTokenSource.token
    });
    
    // Cancel request
    cancelTokenSource.cancel();
    
    0 讨论(0)
  • 2020-12-05 06:56

    https://github.com/axios/axios#cancellation

    const CancelToken = axios.CancelToken;
                    const source = CancelToken.source();
                    let url = 'www.url.com'
    
    
                    axios.get(url, {
                        progress: false,
                        cancelToken: source.token
                    })
                        .then(resp => {
    
                            alert('done')
    
                        })
    
                    setTimeout(() => {
                        source.cancel('Operation canceled by the user.');
                    },'1000')
    
    0 讨论(0)
提交回复
热议问题