您好,在给定大量 json 对象的情况下,我在 NodeJS 上执行 HTTP 请求时遇到问题。给定小的 json 对象数组,请求工作正常。但是,如果我尝试增加 json 数组的大小,我会收到错误:套接字挂断 {"error":{"code":"ECONNRESET"}}。是否需要执行多次写入?还是另一端出了什么问题?
在此先感谢您抽出宝贵时间!
// 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();
最佳答案
您可以流式传输请求正文。
如果 buf
中的数据在 readable stream 中然后你可以做 buf.pipe(req)
。
例如,如果当前目录包含一个文件data.json
,你可以这样做
var buf = fs.createReadStream(__dirname + '/data.json');
创建一个 ReadStream 对象。然后你可以通过管道将其传递给你的请求
buf.pipe(req);
管道命令将在完成流后调用 req.end
。
关于javascript - NodeJS HTTP 请求 POST ERROR socket 挂断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19787883/