Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

JSON Request Body
{
    "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.

Remember: The request body contains the data sent by the client. The HTTP method tells the server what operation is requested.

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.
Important: Do not parse the body before all required chunks have been received. For simple examples, collect the chunks in the data event and process them in the end event.

5. Basic Syntax for Reading a POST Body

The following example demonstrates the basic pattern for collecting request data in Node.js.

JavaScript
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

JavaScript
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

Terminal
node server.js

Step 3: Send a POST Request

In Postman, select POST and enter the following URL.

URL
http://localhost:3000/submit

Select Body → raw → Text and enter:

Request Body
Hello Node.js

Expected Terminal Output

Output
Server running on port 3000
Received Body: Hello Node.js

Expected Client Response

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

JavaScript
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

JSON
{
    "name": "Pradnya",
    "course": "Node.js"
}

Expected Response

JSON 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.

Remember: Set Body → raw → JSON in Postman when testing this example. This program demonstrates receiving data; it does not save the student information to a database.

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

JavaScript
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

JSON
{
    "name": "Samadhan",
    "course": "Node.js"
}

Example of Invalid Request Body

JSON
{
    "name": "",
    "course": "Node.js"
}

Expected Error Response

JSON Response — HTTP 400
{
    "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.