NodeJS HTTP请求POST ERROR套接字挂起 [英] NodeJS HTTP request POST ERROR socket hang up

查看:902
本文介绍了NodeJS HTTP请求POST ERROR套接字挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我在NodeJS上遇到更大数量的json对象时遇到问题。给定json对象的小数组,请求工作正常。但是,如果我尝试增加json的size数组,我收到错误:socket hang up {error:{code:ECONNRESET}}。是否需要执行多次写入?或者在另一端发生了什么问题?

Hi I'm having problems to perform HTTP request on NodeJS given a larger number array of json object. The request works fine given small array of json object. However, if I try to increase the size array of json, I received Error: socket hang up {"error":{"code":"ECONNRESET"}}. Is it required to perform multiple write? Or is it something wrong going on at the other end?

提前感谢您抽出宝贵时间!

Thanks in advance for taking your time here!

    // data is a json object

    var post_data = JSON.stringify(data);
    var buf = new Buffer(post_data);
    var len = buf.length;

    var options = {
        hostname: address,
        port: port,
        path: pathName,
        method: 'PUT',
        headers: {
            'Content-Type':'application/json',
            'Content-Length': len,
            'Transfer-Encoding':'chunked'
        }
    };

    // http call to REST API server
    var req = restHttp.request(options, function(res) {

        console.log('server PUT response received.');
        var resData = '';
        res.on('data', function(replyData) {

            // Check reply data for error.
            console.log(replyData.toString('utf8'));
            if(replyData !== 'undefined')
                resData += replyData;
        });

        res.on('end', function() {          
            callback(JSON.parse(resData));
        });
    }); 


    req.write(buf);
    req.end();


推荐答案

您可以流式传输请求正文。

You can stream the request body.

如果 buf 中的数据位于可读流然后你可以做 buf.pipe(req)

If the data in buf was in a readable stream then you can just do buf.pipe(req).

例如,如果当前目录包含一个文件 data.json ,您可以使用JSON

For example, if the current directory contains a file data.json with the JSON you can do

var buf = fs.createReadStream(__dirname + '/data.json');

创建一个ReadStream对象。然后你可以把它管道给你req

to create a ReadStream object. Then you can pipe this to you req

buf.pipe(req);

管道命令将调用 req.end 一旦完成流式传输。

The pipe command will call req.end once its done streaming.

这篇关于NodeJS HTTP请求POST ERROR套接字挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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