Handle Form Request in Node.js
When a form is submitted using the POST method, data is sent in chunks. To handle this in Node.js, we use two important events: on('data')
and on('end')
.
Get data from request
We collect incoming data chunks into a buffer:
let dataBody = [];
req.on("data", (chunk) => {
dataBody.push(chunk);
});
Handle data with Buffer
Once all data is received, we combine and convert it to a string:
req.on("end", () => {
let rawData = Buffer.concat(dataBody).toString();
console.log(rawData);
});
resp.write(`<h1> Data Submitted </h1>`);
Make request data readable
To parse this string into key-value pairs, use Node's built-in querystring
module:
const querystring = require("querystring");
req.on("end", () => {
let rawData = Buffer.concat(dataBody).toString();
let readableData = querystring.parse(rawData);
console.log(readableData);
});
Notes
on('data')
collects the chunkson('end')
finalizes the dataquerystring.parse()
makes the data easier to use