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

独自空忆成欢 提交于 2019-12-10 18:54:12

问题


OK so in the below example I request something from a server. If a response comes back I parse the JSON and add the data to my mongodb.

However if NO response comes back, then no event fires evidently. How would I add a timeout to this so that if no response is received, then I can cancel the request without any errors being thrown, and call a function? (I'm going to make it call a function that emails me.)

Thanks!

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());
                    }
                );
            }
        });
    });

回答1:


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

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


来源:https://stackoverflow.com/questions/21872833/in-node-js-if-no-response-is-received-from-an-http-request-how-do-you-know

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!