In node.js, if no response from HTTP is received, how do you know?

OK, so in the example below I am requesting something from the server. If the answer comes back, I will parse the JSON and add the data to my mongodb.

However, if the NO response is returned, then no event fires, obviously. How to add a timeout to this so that if no response is received, I can cancel the request without any errors and call the function? (I'm going to get him to call a function that sends me an email.)

Thank!

var req = https.request(options, function(res) {
        res.on('data', function(d) {
            if(d) buffer += d;
        });

        res.on('end', function(){
            var validResponse = true;
            var object;
            try {
                object = JSON.parse(buffer);
            } catch (err) {
                console.log('response: '+ buffer);
                console.log('error in response: ' + err);
                validResponse = false;
            }
            if(validResponse) {
                db.stuff.update(
                    {stuff: "MyStuff"},
                    {stuff: "MyStuff", foo: object.bar},
                    {upsert: true},
                    function() {
                        var time2 = new Date();
                        console.log('db successfully updated db at '+time2.toTimeString());
                    }
                );
            }
        });
    });
+3
source share
1 answer

You can use request.setTimeout(timeout, [callback]) api .

req.setTimeout(5000, function() {  
  console.log('timed out');
  req.abort();
});
+2
source

All Articles