简体   繁体   English

嵌套回调中的nodejs套接字挂断错误

[英]nodejs socket hang up error in nested callback

I try to put many callbacks in a callback, but the program will shut down after the return of several success requests and post "socket hang up" error. 我尝试在回调中放入许多回调,但是该程序将在返回多个成功请求后关闭,并显示“套接字挂起”错误。 I try to collect data from response and output them at once, can someone tell me which part goes wrong... By the way, I hide the details of request method, I promise the request method works on http call. 我尝试从响应中收集数据并立即输出它们,有人可以告诉我哪一部分出了问题...顺便说一下,我隐藏了请求方法的详细信息,我保证请求方法可用于http调用。

http.request(options1,function(data){
    var condition=data.length;
    var result=[];
    data.foreach(item,function(data){
        http.request(options2, function(data){
             if(data) result.push(data);
             condition--;
             if(condition<=0) console.log(result);
        }
    });
});

for my http.request method 为我的http.request方法

var request=function(options,callback){
    http.request(options,function(res){
        var body;

        res.on('data',function(chunk){
             body+=chunk;
        });
        res.on('end',function(){
             callback(JSON.parse(body));
        });

    request.end();
};

That's not the correct usage of http.request() . 那不是http.request()的正确用法。

  • The http.request() callback is passed an IncomingMessage object, not buffered response data. http.request()回调传递了IncomingMessage对象,而不是缓冲的响应数据。

    • EDIT: Your custom request() should look something like this, although you should handle errors too. 编辑:您的自定义request()应该看起来像这样,尽管您也应该处理错误。 Note the proper placement of request.end() and initializing var body = '' : 注意request.end()的正确位置并初始化var body = ''

       function request(options, callback) { http.request(options,function(res) { var body = ''; res.setEncoding('utf8'); res.on('data',function(chunk) { body += chunk; }).on('end',function() { callback(JSON.parse(body)); }); }).end(); } 
  • You're missing .end() for your requests so that node.js knows you are ready to actually send the HTTP request: http.request(..., ....).end(); 您缺少请求的.end() ,因此node.js知道您已经准备好实际发送HTTP请求: http.request(..., ....).end(); . This is the cause of your particular error... the server hangs up the connection because it got tired of waiting for your request after the TCP connection was opened. 这是造成您特定错误的原因...服务器挂断了连接,因为在打开TCP连接后,它厌倦了等待您的请求。

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

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