Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NODE JS cancel request

I am using this code to download files in node js :

var currentVideoRequest = null;

window.spawnVideoPlayer = function (url, subs, movieModel,tag) {
    if(currentVideoRequest) {
    try
    {
      currentVideoRequest.abort();
    }
    catch(err)
    {
      alert(err.message);
    }

    }

    var fs = require('fs');
    var urlrequest = currentVideoRequest = require('request');

    urlrequest.get({url: url, encoding: 'binary'}, function (err, response, body) {
      fs.writeFile(FILEURL, body, 'binary', function(err) {

      }); 
    });
}

And in the currentVideoRequest.abort(); i get this error:

    Object function request(uri, options, callback) {
  if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.')
  if ((typeof options === 'function') && !callback) callback = options
  if (options && typeof options === 'object') {
    options.uri = uri
  } else if (typeof uri === 'string') {
    options = {uri:uri}
  } else {
    options = uri
  }

  options = copy(options)

  if (callback) options.callback = callback
  var r = new Request(options)
  return r
} has no method 'abort'
like image 972
YosiFZ Avatar asked Apr 16 '14 08:04

YosiFZ


People also ask

How do I cancel HTTP request?

We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won't be sent if the cancellation signal is sent before the HTTP request is done.

How do I cancel a Node js request?

We're passing cancelRequest. signal (an AbortSignal instance) as a signal option to the fetch() function. This will allow us to abort the HTTP request which fetch() makes. We're calling the abort() method on our cancelTimeout abort controller when our request has completed.

What is RES end in Node js?

res. end() will end the response process. This method actually comes from Node core, specifically the response. end() method of http. ServerResponse .

What is setHeader in Node js?

setHeader(name, value) (Added in v0. 4.0) method is an inbuilt application programming interface of the 'http' module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced.


Video Answer


4 Answers

To add to @Etai's answer, you need to require the request module before using it for one instance of the request. Something like this:

var request = require('request');
// ...
// then later in the code
var urlrequest = request.get(uri, function(err, response, body) {
    // process data here
});

// later, you'd abort this as:
urlrequest.abort();

Note that I'm saving the instance with var urlrequest = request.get(params, callback); so that I can call abort on it later.

like image 89
Zlatko Avatar answered Oct 20 '22 01:10

Zlatko


your currentVideoRequest is a constructor for a request object, not a request object, which is why this is failing.

The request constructor returns a request object when invoked, i.e.

require('request')('uri', function(err, resp, body){})
like image 34
Etai Avatar answered Oct 19 '22 23:10

Etai


I think you can use this method to get what you need. I used async in this way, which makes both the code cleaner and less callback .

(async function main() {
    try {
        let urlRequest = await customRequest("http://127.0.0.1:8000/api/product/search?title=foo");
        urlRequest.abort();
    } catch (e) {
        console.log(e);
    }
})();

function customRequest(url) {
    return new Promise((resolve, reject) => {
        request.get(url, (err, res) => {
            if (err) reject(err)
            if (res.statusCode !== 200)
                reject("my Error ");

            resolve(res);
        })
    })
}


Also, if you do not need to answer the urlRequest variable,you can remove the await from the function as shown below.

try {
        let urlRequest =  customRequest("http://127.0.0.1:8000/api/product/search?title="); // run in background !
        urlRequest.abort();
    } catch (e) {
        console.log(e);
    }

Finally, since our request returns an exception if you make a mistake, you can write abort() in the catch block if needed.

(async function main() {
    try {
        var urlRequest =await  customRequest("http://127.0.0.1:8000/api/product/search?title=");
    } catch (e) {
        urlRequest.abort();
        console.log(e);
    }
})();

Also, because the customRequest() function returns a promise note, you use then() instead of async await.

like image 43
Amir Avatar answered Oct 20 '22 01:10

Amir


you can use abort() method to stop that request.

var reqObj = request({uri: 'https://jsonplaceholder.typicode.com/albums'  }, function (error, response, body) {
    console.log('API requested ') ;
    if (!err){
        console.log(body);
    }
    else
    {
        console.log(err);
    }
});

reqObj.abort();
like image 27
Osama Bari Avatar answered Oct 20 '22 01:10

Osama Bari