简体   繁体   English

在node.js中异步https请求

[英]Async https requests in node.js

I've got an app that fires off https requests to a 3rd party service to perform logging. 我有一个可以触发对第三方服务进行记录的https请求的应用。 For some reason or another I noticed a few hours ago that the 3rd party is refusing the connections. 出于某种原因,几个小时前,我注意到第三方拒绝连接。 That's a different topic though. 但是,这是一个不同的话题。

What I'm noticing in my node.js app is that despite the requests being created dynamically, and therefore shouldn't be hanging the entire app, they are. 我在我的node.js应用程序中注意到的是,尽管请求是动态创建的,因此不应该挂起整个应用程序,而是这样。

After a restart of the process, the https request is hanging and then dies with a connection refused error. 重新启动该过程后,https请求挂起,然后死于连接拒绝错误。 Sample code is below. 示例代码如下。

var logger = function(data){

    var req = https.request({
        host: 'logs.loggly.com',
        port: 443,
        path: '/inputs/<my real key is here, removed obviously>',
        method: 'POST',
        headers:{
            'content-type': 'application/json'
        }
    }, function(res){
        var body = [];
        res.on('chunk', function(data){
            body.push(data);
        });
        res.on('end', function(){
            console.log(body.join(''));
        })
    });
    req.write(JSON.stringify(data));
    req.end();

}

And that's called simply by: 这简单地称为:

logger({ 'test': 'datafoo' });

So I'm curious why a connection refused/timeout from this outbound https request should be hanging and then crashing the entire app. 所以我很好奇为什么此出站https请求的连接被拒绝/超时应该挂起然后导致整个应用崩溃。

Thanks! 谢谢!

The program hangs and prints nothing because it's not catching data and you're not telling the process to do anything but print an empty string with [].join('') . 该程序挂起并且不打印任何内容,因为它没有捕获数据,并且您没有告诉进程执行任何操作,而是使用[].join('')打印空字符串。 Node.js won't return without explicit instruction on IO-bound tasks. 没有关于IO绑定任务的明确指示,Node.js不会返回。 You need to pass in and execute a callback function, or call process.exit(); 您需要传递并执行回调函数,或调用process.exit(); , in the handler for res.on("end", [handler]); ,在res.on("end", [handler]); , eg: ,例如:

res.on("end", function() {
    console.log(body.join(''));
    process.exit();
});

res.on("chunk", [handler]); isn't a standard HTTPS event. 不是标准的HTTPS事件。 You likely intended something like res.on("data", function(chunk) { body.push(chunk); }); 您可能打算使用类似res.on("data", function(chunk) { body.push(chunk); }); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM