Handling POST request in Node.js
suggest changeRemarks
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
- Each
datachunk is a Buffer. - Create the accumulator inside the request handler so requests do not share one body.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents