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 handle in request body of a POST request, use the request
object, which is a readable stream. Data streams are emitted as data
events on the request
object.
request.on('data', chunk => {
buffer += chunk;
});
request.on('end', () => {
// POST request body is now available as `buffer`
});
Simply create an empty buffer string and append the buffer data as it received via data
events.
NOTE
data
events is of type Bufferbuffer
string inside the request handler.'use strict';
const http = require('http');
const PORT = 8080;
const server = http.createServer((request, response) => {
let buffer = '';
request.on('data', chunk => {
buffer += chunk;
});
request.on('end', () => {
const responseString = `Received string ${buffer}`;
console.log(`Responding with: ${responseString}`);
response.writeHead(200, "Content-Type: text/plain");
response.end(responseString);
});
}).listen(PORT, () => {
console.log(`Listening on ${PORT}`);
});