我正在尝试计算文件上传的进度,所以我使用的是Superagent。我能够获得文件上传的进度。
现在,当用户选择取消按钮时,我需要中断或取消发布请求。有没有办法做到这一点。以下是我的代码:
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);
})
经过一些研究,我能够找到如何interrupt
或cancel
或abort
一个superagent request。以下代码将起作用:
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);
})
来自他们的docs的其他信息
.abort()
应该中止请求
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);
应该允许链接.abort()几次
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);
选定的答案不再正确。也不是superagent的文件,提到一个模糊的req
变量,这是无处可定义的。
事实是 :
.end()
返回undefined
(since this commit).then()
返回一个承诺.end()
或多或少被弃用,其文档错误:
/*
* 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();
};
解:
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);