reactjs - interrupting a post request in superagent

Viewed 3735

I am trying to calculate the progress of a file upload, so I was using Superagent. I was able to get the progress of the file upload.

Now when a user selects the cancel button, I need to interrupt or cancel the post request. Is there any way to do that. The following is my code:

var file = somefile.pdf
Request.post('http://posttestserver.com/post.php?dir=example')
  .set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
  .send(file)
  .on('progress', function(e) {
    console.log('Progress', e.percent);
  })
  .end((err, res) => {
      console.log(err);
      console.log(res);
  })
3 Answers

Selected answer is not correct anymore. Nor is superagent's doc, mentionning a vague req variable which is nowhere defined.

Truth is :

.end() is more or less deprecated and its documentation is wrong:

    /*
     * Initiate request, invoking callback `fn(res)`
     * with an instanceof `Response`.
     *
     * @param {Function} fn
     * @return {Request} for chaining
     * @api public
     */

    Request.prototype.end = function (fn) {
      if (this._endCalled) {
        console.warn("Warning: .end() was called twice. This is not supported in superagent");
      }
      this._endCalled = true;

      // store callback
      this._callback = fn || noop;

      // querystring
      this._finalizeQueryString();

      this._end();
    };

Solution:

var chain = request.get(uri + '/delay/3000');

chain.end(function(err, res){
    try {
        assert(false, 'should not complete the request');
    } catch(e) { done(e); }
});

setTimeout(function() {
    chain.req.abort();
}, 1000);

Trying to figure out how to get cancel working with promises I did the following:

var req = request.get('/');

req.then((response) => { 
  // do work 
}).catch((error) => {});

req.xhr.abort();
Related