Handling POST Body in Node.js
Learn how to receive, read, validate and process data sent by clients through POST requests using the built-in Node.js HTTP module.
When a user submits a registration form, the client sends information to the server. For example, Pradnya wants to register for a Node.js course at CIIT Training Institute. Her name and course details can be sent in the HTTP request body using the POST method.
Node.js provides the request object req to
receive incoming data. Since the request body is a stream,
we can collect its chunks and process the complete body
when the request's end event occurs.
1. What Is a POST Request Body?
A POST request body contains the data that a client sends to a server. This data may include form information, student details, product information or other application data.
For example, Pradnya submits the following student information to the CIIT Training Institute server.
{
"name": "Pradnya",
"course": "Node.js"
}
The server receives this JSON as text, converts it into a JavaScript object and can then validate or process the values.
2. Why Do We Handle a POST Body?
Servers need to read the request body when clients submit information that the server must validate or process.
| Scenario | Data Sent | Purpose |
|---|---|---|
| Student registration | Name and course | Register a student. |
| Product creation | Product name and price | Create a product record. |
| Contact form | Name and message | Receive a user's message. |
| Login form | Username and password | Submit authentication information securely. |
3. How Does POST Body Handling Work?
The client sends the request body to the server. Node.js receives the incoming data as stream chunks. The server collects these chunks and processes the complete body after the request ends.
1. Client
Pradnya submits the student registration form.
2. POST Request
Sends JSON data to the server.
3. Receive Data Chunks
Use req.on("data").
4. Process Complete Body
Use req.on("end") and parse JSON.
5. Send Response
Return the result with an appropriate status code.
4. Understanding the Request Stream
In Node.js, the incoming HTTP request is a readable stream. The request body may arrive in multiple chunks rather than one complete piece of data.
Important Request Events
| Event | Purpose |
|---|---|
data |
Emitted when a chunk of request data is received. |
end |
Emitted when the request body stream has ended. |
error |
Can report an error from the readable stream. |
5. Basic Syntax for Reading a POST Body
The following example demonstrates the basic pattern for collecting request data in Node.js.
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
console.log("Received Body:", body);
});
Understanding the Code
| Code | Explanation |
|---|---|
let body = "" |
Creates an empty string to collect incoming data. |
req.on("data", ...) |
Receives each data chunk. |
body += chunk |
Adds the received chunk to the body string. |
req.on("end", ...) |
Processes the body after the stream ends. |
console.log(body) |
Displays the collected body in the terminal. |
6. First Program: Read a POST Body
Let's create a simple server that reads the request body sent by a client and returns the received text.
Step 1: Create server.js
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/submit") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
console.log("Received Body:", body);
res.writeHead(200, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("POST body received successfully");
});
} else {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8"
});
res.end("Route not found");
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Step 2: Run the Server
node server.js
Step 3: Send a POST Request
In Postman, select POST and enter the following URL.
http://localhost:3000/submit
Select Body → raw → Text and enter:
Hello Node.js
Expected Terminal Output
Server running on port 3000
Received Body: Hello Node.js
Expected Client Response
POST body received successfully
Explanation:
The server accepts POST requests sent to
/submit, collects the body and prints it in
the terminal. After receiving the complete body, it sends
a success response to the client.
7. Handling a JSON POST Body
APIs commonly receive JSON data. To work with JSON values,
we first collect the request body as text and then convert
it into a JavaScript object using JSON.parse().
Example: Receiving Student Details
const http = require("node:http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/students") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const student = JSON.parse(body);
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify({
message: "Student data received successfully",
student: student
}));
} catch (error) {
res.writeHead(400, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify({
message: "Invalid JSON body"
}));
}
});
} else {
res.writeHead(404, {
"Content-Type": "application/json; charset=utf-8"
});
res.end(JSON.stringify({
message: "Route not found"
}));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Request Body
{
"name": "Pradnya",
"course": "Node.js"
}
Expected Response
{
"message": "Student data received successfully",
"student": {
"name": "Pradnya",
"course": "Node.js"
}
}
Explanation:
JSON.parse(body) converts valid JSON text into
a JavaScript object. If the body contains invalid JSON,
parsing throws an error and the catch block returns
status code 400.
8. Validating the POST Body
A server should not accept every value sent by a client. It should check whether required fields exist and whether their values are valid before processing the data.
For example, the student registration endpoint should reject a request when the name or course is missing.
Example: Validate Student Data
const http = require("node:http");
const server = http.createServer((req, res) => {
res.setHeader(
"Content-Type",
"application/json; charset=utf-8"
);
if (req.method !== "POST" || req.url !== "/students") {
res.writeHead(404);
res.end(JSON.stringify({
message: "Route not found"
}));
return;
}
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
try {
const student = JSON.parse(body);
if (
!student ||
typeof student !== "object" ||
Array.isArray(student)
) {
res.writeHead(400);
res.end(JSON.stringify({
message: "A JSON object is required"
}));
return;
}
if (
typeof student.name !== "string" ||
!student.name.trim() ||
typeof student.course !== "string" ||
!student.course.trim()
) {
res.writeHead(400);
res.end(JSON.stringify({
message: "Name and course are required"
}));
return;
}
res.writeHead(201);
res.end(JSON.stringify({
message: "Student details validated successfully",
student: {
name: student.name.trim(),
course: student.course.trim()
}
}));
} catch (error) {
res.writeHead(400);
res.end(JSON.stringify({
message: "Invalid JSON body"
}));
}
});
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});
Valid Request Body
{
"name": "Samadhan",
"course": "Node.js"
}
Example of Invalid Request Body
{
"name": "",
"course": "Node.js"
}
Expected Error Response
{
"message": "Name and course are required"
}
Explanation: The program checks that the body is a JSON object and that both name and course are non-empty strings. Valid input receives status code 201 in this example, while invalid input receives status code 400.
9. POST Body Processing Flow
The following flow summarizes how a server processes a JSON POST body.
Receive POST Request
Check the method and URL.
Collect Body
Append chunks received through the data event.
Parse JSON
Convert the text into a JavaScript value.
Validate Data
Check required fields and their values.
Send Response
Return an appropriate status code and message.
10. Important Points
- POST requests commonly send data in the request body.
- Node.js receives request-body data through a readable stream.
- The data event provides incoming chunks.
- The end event indicates that the request stream has ended.
-
Use
JSON.parse()to parse valid JSON text. - Handle invalid JSON using try/catch.
- Validate request data before processing it.
- Production applications should also limit request-body size and handle stream errors.
Summary
In this lesson, we learned how to handle POST request bodies using Node.js's built-in HTTP module. We collected incoming chunks through the data event, processed the complete body through the end event, converted JSON text into a JavaScript object, and validated the received data. These concepts are essential when building HTTP APIs that accept information from clients.