Handling POST request in Node.js

suggest change

Remarks

Node.js uses streams to handle incoming data.

Quoting from the docs,

A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface.

To read the body of a POST request, use the request object, which is a readable stream. Chunks arrive as data events.

let body = '';
request.on('data', chunk => {
  body += chunk;
});
request.on('end', () => {
  // POST request body is now available as `body`
});

Start a new string for every request and append each chunk. chunk is a Buffer; += decodes it as UTF-8, so this form is for text. For binary bodies, push the chunks into an array and join them with Buffer.concat.

NOTE

  1. Each data chunk is a Buffer.
  2. Create the accumulator inside the request handler so requests do not share one body.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents