Request: How to abort a request?

Created on 15 Jan 2014  ·  5Comments  ·  Source: request/request

I had been trying to abort a request for hours, can anyone help me please?

This is what I have:

app.get('/theUrl', function (req, resp) {

  var parser = new Transform();
  parser._transform = function(data, encoding, done) {
    var _this = this;
    // Process data here
  }.on("error", function(err){
        console.log(err);
      });

  var theRequest = request({
    'method' : 'GET',
    'url': '/anotherUrl',
    'headers' : {
      "ACCEPT"  : "text/event-stream"
    }
  }, function (error, response, body){
    if (error) {
      //Throw error
    }
  }).pipe(parser).pipe(resp);

  req.on("close", function(){
    parser.end();
    theRequest.abort(); //Doesn't work
  });
});

As you can see its kinda a streaming proxy, so if clients cancels the request I catch it and need to close or abort the forwarding request (theRequest).

Any ideas?

Thanks!

Most helpful comment

var r = request(url)
r.abort()

We should get this in to the documentation.

All 5 comments

var r = request(url)
r.abort()

We should get this in to the documentation.

Thanks for the reply @mikeal, I tried this:

var theRequest = request({
  'method' : 'GET',
  'url': '/anotherUrl',
  'headers' : {
    "ACCEPT"  : "text/event-stream"
  }
}, function (error, response, body){
  if (error) {
    //Handle error
  }
}).pipe(parser);

theRequest.abort();

And this error raises:

/home/vagrant/gateway/app.js:876
      theRequest.abort();
                 ^
TypeError: Object #<ServerResponse> has no method 'abort'
    at IncomingMessage.<anonymous> (/home/vagrant/gateway/app.js:876:18)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at abortIncoming (http.js:1912:11)
    at Socket.socket.onend (http.js:2010:7)
    at Socket.g (events.js:180:16)
    at Socket.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

Could you help me please?

Thank you!

From the docs:

pipe() returns the destination stream

so you are no longer working with a Request object. In this case you're calling abort() on a ServerResponse. Do this instead:

var theRequest = request({ ... });

theRequest.pipe(parser);

theRequest.abort();

Thanks a lot!

Thanks a lot!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Fov6363 picture Fov6363  ·  24Comments

danielgindi picture danielgindi  ·  20Comments

dcsan picture dcsan  ·  19Comments

ovk picture ovk  ·  26Comments

Areks picture Areks  ·  77Comments