Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs - interrupting a post request in superagent

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);
  })
like image 850
Jeril Avatar asked Dec 05 '22 14:12

Jeril


1 Answers

After some research I was able to find out how to interrupt or cancel or abort a superagent request. The following code will work:

var file = somefile.pdf
var req = 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) {
    if (condition) {
      req.abort() // to cancel the request
    }
    console.log('Progress', e.percent);
  })
  .end((err, res) => {
      console.log(err);
      console.log(res);
  })

Additional information from their docs

.abort()

should abort the request

var req = request
  .get(uri + '/delay/3000')
  .end(function(err, res){
    try {
    assert(false, 'should not complete the request');
    } catch(e) { done(e); }
      });
  req.on('error', function(error){
    done(error);
  });
  req.on('abort', done);
  setTimeout(function() {
    req.abort();
  }, 500);

should allow chaining .abort() several times

var req = request
  .get(uri + '/delay/3000')
  .end(function(err, res){
    try {
    assert(false, 'should not complete the request');
    } catch(e) { done(e); }
  });
  // This also verifies only a single 'done' event is emitted
  req.on('abort', done);
  setTimeout(function() {
    req.abort().abort().abort();
  }, 1000);
like image 137
Jeril Avatar answered Dec 24 '22 22:12

Jeril