NodeJS + miekal / request: how to abort a request?

I have been trying to cancel the request for several hours, can anyone help me?

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 kind of streaming proxy, so if the clients cancel the request, I will catch it and you need to close or abort the forwarding ( theRequest

) request .

Any ideas?

Thank!

0


source to share


1 answer


Quoting nylen from https://github.com/mikeal/request/issues/772#issuecomment-32480203 :

From the docs:

pipe () returns the target stream



so that you don't work with the Request object anymore. In this case, you call abort () on ServerResponse. Do this instead:

var theRequest = request({ ... });
theRequest.pipe(parser);
theRequest.abort();

      

And it all worked.

0


source







All Articles