Large strings are not completely passing from client to server by POST method in node

I understood why this is happening. It’s bcoz node receives large request datas in chunks, and so I got partial JSON data, and Node threw error.

For testing purposes, one can check the following code on localhost:

  • index.js
let http = require('http'),
    fs = require('fs');

http.createServer((req, resp) => {
  if(req.method === 'GET' && req.url === '/') {
    fs.readFile('./index.html', (err, res) => {
      resp.writeHead('200', { 'Content-Type': 'text/html' });
      resp.end(res, 'utf8');
    });
  } else if(req.method === 'POST') req.on( 'data', chunk => console.log('Length', chunk.length) );
}).listen(8080);
  • index.html
<input type="file" accept="image/*" onchange="f(this);">
<script>
function f(el) {
	var fr = new FileReader();
	fr.onload = function() {
		console.log('Length', fr.result.length);
		var xhr = new XMLHttpRequest();
		xhr.open('POST', '/', true);
		xhr.send(fr.result);
	};
	fr.readAsDataURL(el.files[0]);
};
</script>

A handy solution

Write something like,

let chunk = '';
req.on('data', _chunk => chunk += _chunk).on('end', () => {
  // do something with chunk
});
1 Like