在node.js中如果没有收到来自http请求的响应,你怎么知道? [英] In node.js if no response is received from an http request, how do you know?

查看:160
本文介绍了在node.js中如果没有收到来自http请求的响应,你怎么知道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,在下面的示例中,我向服务器请求了一些内容。如果响应回来,我解析JSON并将数据添加到我的mongodb。

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.)

谢谢!

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


推荐答案

您可以使用请求。 setTimeout(超时,[回调]) api

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

这篇关于在node.js中如果没有收到来自http请求的响应,你怎么知道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆