Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: how to stop an already started http request

We use request to make http requests with node.js. We would like to give the user an opportunity to abort the request when he decides. That means we have to trigger the abort() from outside the request function. Maybe we can check an outside variable from inside the function. (We already tried to set the timeout to zero after the request started, that doesn't work.) Maybe we set the variable request to null. Do you know a better way to do this?

here is example code to show what kind of request we are talking about:

app.js:

var http = require('http'); var request = require("request");  http.createServer().listen(1337, "127.0.0.1");  request({uri: 'http://stackoverflow.com'  }, function (error, response, body) {     console.log('url requested ') ;     if (!error){         console.log(body);     }     else     {         console.log(error);     } }); 
like image 295
Michael Moeller Avatar asked Apr 01 '13 16:04

Michael Moeller


People also ask

How do I stop a node js request?

destroy() really works, uncomment it, and the response object will keep emitting events until it closes itself (at which point node will exit this script).

How do I terminate HTTP request?

You can abort the current HTTP request using the abort() method, i.e., after invoking this method, on a particular request, execution of it will be aborted. If this method is invoked after one execution, responses of that execution will not be affected and the subsequent executions will be aborted.

How do I stop HTTP server in node JS?

The server. close() method stops the HTTP server from accepting new connections. All existing connections are kept.

Does node js server block HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.


1 Answers

The request function returns a request object. Just call abort() on that?

var r = request({uri: 'http://stackoverflow.com'  }, function (error, response, body) {     console.log('url requested ') ;     if (!error){         console.log(body);     }     else     {         console.log(error);     } });  r.abort(); 
like image 111
Jason Harwig Avatar answered Sep 22 '22 22:09

Jason Harwig