reactjs - 在superagent中断一个post请求

时间:2017-05-22 17:52:59

标签: javascript reactjs superagent

我正在尝试计算文件上传的进度,因此我使用的是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);
  })

3 个答案:

答案 0 :(得分:2)

经过一些研究后,我能够了解如何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);
  })
  

来自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);

答案 1 :(得分:1)

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

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

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

req.xhr.abort();

答案 2 :(得分:0)

所选答案不再正确。 超级代理人的文档也没有提到一个模糊的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);