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);
})
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With