NodeJS将POST请求正文截断到服务器

时间:2021-06-18 01:48:11

标签: node.js http stream buffer

我有以下代码:


const http = require('http');
const { Readable } = require('stream');

const hostname = 'hostname';
const port = 3000;
const path = '/my/path';
const method = 'POST';

const body = JSON.stringify(VERYLARGEJSONOBJECT); // 343700+ bytes in size

console.log(`Sending ${body.length} bytes:`);

const options = {
hostname,
port,
path,
method,
headers: {
  'Content-Type': 'application/json',
  'Content-Length': body.length
  }
};

const req = http.request(options, (res) => {
  console.log(`Response statusCode: ${res.statusCode}`);
});

const stream = Readable.from([body]);

stream.pipe(req);

req.on('error', (error) => {
  console.error(error);
});

当我从我的桌面(x64,16GB RAM)发送它时,它甚至可以发送最大的 JSON 对象。但是当我从旧的 i3 笔记本电脑(8GB RAM)发送它时,JSON 对象被切断,并且无法被接收服务器解析。

我认为这与我用来缓冲输出的流有关(因为 req.write 很快就会饱和),但无法确切地弄清楚我哪里出错了。

>

我知道是这个发送代码是错误的,因为我可以使用邮递员发送相同的 JSON 对象,或者在我的桌面上使用完全相同的代码发送到服务器并且它工作得很好。

我也试过用以下方法分割 JSON 数据:

  const body = JSON.stringify(VERYLARGEJSONOBJECT); // 343700+ bytes in size
  var re = new RegExp('.{1,' + 512 + '}', 'g');
  const packetChunks = body.match(re);

...

  const stream = Readable.from(packetChunks);

但没有帮助

编辑:

进一步查了一下,好像只有最后3个字符丢失了,只有在i3机器上调用的时候,很奇怪。 客户端将 "inetLatency":17.996} 作为 JSON 数据包的最后一部分发送,但服务器正在接收 "inetLatency":17.9。我已经尝试在最后添加一个 req.write(' ');(它返回 true)并且也没有调用 req.end() 来查看这是否会使服务器接收到尾随数据,但它仍然没有没有收到任何东西。

将 stringify 行更改为 const body = JSON.stringify(sendData) + ' '; 确实可以确保接收到 JSON 对象的最后 3 个字符,但我不喜欢这种 hack,因为它不能解决下划线问题。

0 个答案:

没有答案