reactjs - 中断 superagent 中的 post 请求

reactjs - interrupting a post request in superagent

我正在尝试计算文件上传的进度,所以我使用了 Superagent。我能够得到文件上传的进度。

现在,当用户选择取消按钮时,我需要中断或取消 post 请求。有什么办法可以做到这一点。以下是我的代码:

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);
  })

经过一番研究,我找到了如何 interruptcancelabortsuperagent 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);
  })

Additional information from their 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() 或多或少已被弃用,其文档有误:

    /*
     * 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);

为了弄清楚如何使用 promise 取消工作,我做了以下事情:

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

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

req.xhr.abort();