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

HTTP Request Methods in Node.js

Learn how HTTP request methods work in Node.js, how clients communicate with servers, and how to handle GET, POST, PUT, PATCH and DELETE requests using the built-in HTTP module.

HTTP request methods describe the type of operation a client wants to perform on a server. For example, at CIIT Training Institute, Samadhan may want to view student details, Pradnya may want to register a new student, and an administrator may need to update or delete a student record.

Node.js provides the built-in http module. Inside the request callback, we can access req.method and req.url to identify the incoming request and decide how the server should respond.

1. What Are HTTP Request Methods?

HTTP request methods are used by clients to tell a server what operation they want to perform. A client can be a browser, a frontend application, Postman or another server.

For example, when Samadhan opens a student list, the client can send a GET request. When Pradnya submits a registration form, the client can send a POST request.

Remember: The HTTP method describes the requested operation. The URL identifies the resource or route being requested.
Method Purpose Example
GET Retrieve or read data. View student details.
POST Submit data or create a resource. Register a new student.
PUT Replace an existing resource. Replace all editable student fields.
PATCH Update selected fields. Change only a student's course.
DELETE Remove a resource. Delete a student record.

2. Why Are HTTP Methods Used?

Different methods help clients and servers communicate the intended operation clearly. They also make API routes easier to understand and maintain.

Scenario HTTP Method Expected Operation
Samadhan views all students. GET Return student information.
Pradnya registers a student. POST Create a student record.
An administrator replaces student details. PUT Replace the editable resource fields.
An administrator changes a student's course. PATCH Update only the specified field.
An administrator removes a student. DELETE Delete the selected record.

3. How Do HTTP Request Methods Work?

The client sends an HTTP request containing a method and a URL. The Node.js server examines the request, performs the required operation and sends an HTTP response.

1. Client

Browser, Postman or frontend application

↓
2. HTTP Request

Method: GET, POST, PUT, PATCH or DELETE

URL: /students

↓
3. Node.js HTTP Server

Checks req.method and req.url

↓
4. Perform Operation

Read, create, replace, update or delete data

↓
5. HTTP Response

Status code, headers and response body

4. Checking the HTTP Method in Node.js

Node.js provides the req.method property to identify the HTTP method used by the client. The req.url property contains the requested URL.

We can use an if...else statement to check the method and execute the appropriate code.

Basic Syntax

JavaScript
const http = require("node:http");

const server = http.createServer((req, res) => {

    console.log("Request Method:", req.method);
    console.log("Request URL:", req.url);

    res.end("Request received");

});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});

Understanding the Code

Code Meaning
require("node:http") Loads Node.js's built-in HTTP module.
http.createServer() Creates an HTTP server.
req.method Provides the HTTP method of the incoming request.
req.url Provides the requested URL.
res.end() Finishes the HTTP response.
server.listen(3000) Starts listening on port 3000.

Expected Terminal Output

Output
Server running on port 3000
Request Method: GET
Request URL: /

Explanation: When we open http://localhost:3000 in a browser, the browser sends a GET request. The server prints the method and URL in the terminal and sends the response text.

5. GET Method in Node.js

The GET method is used to retrieve information from a server. It is commonly used to display records, fetch product details or read student information.

For example, Samadhan wants to see the student details available at CIIT Training Institute. The client sends a GET request to the server.

Example: GET Request

JavaScript
const http = require("node:http");

const server = http.createServer((req, res) => {

    res.setHeader("Content-Type", "application/json; charset=utf-8");

    if (req.method === "GET" && req.url === "/students") {

        const students = [
            { id: 1, name: "Samadhan", course: "Node.js" },
            { id: 2, name: "Pradnya", course: "JavaScript" }
        ];

        res.writeHead(200);
        res.end(JSON.stringify(students));

    } else {

        res.writeHead(404);
        res.end(JSON.stringify({
            message: "Route not found"
        }));

    }

});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});

Test the Request

Browser / Postman
GET http://localhost:3000/students

Expected Output

JSON Response
[
  {
    "id": 1,
    "name": "Samadhan",
    "course": "Node.js"
  },
  {
    "id": 2,
    "name": "Pradnya",
    "course": "JavaScript"
  }
]

Explanation: The server checks whether the method is GET and the URL is /students. If both conditions match, it returns the student list with status code 200.

6. POST Method in Node.js

The POST method is commonly used to submit data to a server or create a new resource. For example, Pradnya submits a registration form to add a student to the system.

Data is often sent in the request body. In Node.js, the incoming request body is a stream, so the server can collect its chunks and process the body when the request ends.

Example: POST Request

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") {

        let body = "";

        req.on("data", chunk => {
            body += chunk;
        });

        req.on("end", () => {

            try {
                const student = JSON.parse(body);

                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 registered successfully",
                    student: {
                        name: student.name.trim(),
                        course: student.course.trim()
                    }
                }));

            } catch {
                res.writeHead(400);
                res.end(JSON.stringify({
                    message: "Invalid JSON body"
                }));
            }

        });

    } else {

        res.writeHead(404);
        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 registered successfully",
    "student": {
        "name": "Pradnya",
        "course": "Node.js"
    }
}

Explanation: The server collects the incoming body using the data and end events. It then parses the JSON and validates the fields. Status code 201 indicates successful creation in this illustrative example.

Important: This example demonstrates request-body handling. It does not store the student in a database or persistent array. A real application should save the validated data to its data store.

7. PUT Method in Node.js

The PUT method is generally used to create or replace a resource at a specified URL. When replacing an existing resource, the client normally sends all the fields needed for that resource.

For example, an administrator wants to replace the editable details of student number 1.

Example: PUT Request

JavaScript
const http = require("node:http");

const server = http.createServer((req, res) => {

    res.setHeader("Content-Type", "application/json; charset=utf-8");

    if (req.method === "PUT" && req.url === "/students/1") {

        let body = "";

        req.on("data", chunk => {
            body += chunk;
        });

        req.on("end", () => {

            try {
                const student = JSON.parse(body);

                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;
                }

                const updatedStudent = {
                    id: 1,
                    name: student.name.trim(),
                    course: student.course.trim()
                };

                res.writeHead(200);

                res.end(JSON.stringify({
                    message: "Student details replaced successfully",
                    student: updatedStudent
                }));

            } catch {
                res.writeHead(400);
                res.end(JSON.stringify({
                    message: "Invalid JSON body"
                }));
            }

        });

    } else {

        res.writeHead(404);
        res.end(JSON.stringify({
            message: "Route not found"
        }));

    }

});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});

Request Body

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

Explanation: The server accepts the complete editable student details, validates the values and constructs a replacement resource. This example returns the replacement in the response; it does not persist it to a database.

8. PATCH Method in Node.js

The PATCH method is used to update only selected fields of a resource instead of replacing the entire resource.

For example, Pradnya wants to change her course from JavaScript to Node.js without changing her name or ID.

Example: PATCH Request

JavaScript
const http = require("node:http");

const student = {
    id: 2,
    name: "Pradnya",
    course: "JavaScript"
};

const server = http.createServer((req, res) => {

    res.setHeader("Content-Type", "application/json; charset=utf-8");

    if (req.method === "PATCH" && req.url === "/students/2") {

        let body = "";

        req.on("data", chunk => {
            body += chunk;
        });

        req.on("end", () => {

            try {
                const updates = JSON.parse(body);
                const allowedFields = ["name", "course"];
                const fields = Object.keys(updates);

                if (
                    !updates ||
                    typeof updates !== "object" ||
                    Array.isArray(updates) ||
                    fields.length === 0 ||
                    fields.some(field => !allowedFields.includes(field))
                ) {
                    res.writeHead(400);
                    res.end(JSON.stringify({
                        message: "Provide valid name or course fields"
                    }));
                    return;
                }

                for (const field of fields) {
                    if (
                        typeof updates[field] !== "string" ||
                        !updates[field].trim()
                    ) {
                        res.writeHead(400);
                        res.end(JSON.stringify({
                            message: field + " must be a non-empty string"
                        }));
                        return;
                    }
                }

                for (const field of fields) {
                    student[field] = updates[field].trim();
                }

                res.writeHead(200);

                res.end(JSON.stringify({
                    message: "Student details updated successfully",
                    student: student
                }));

            } catch {
                res.writeHead(400);
                res.end(JSON.stringify({
                    message: "Invalid JSON body"
                }));
            }

        });

    } else {

        res.writeHead(404);
        res.end(JSON.stringify({
            message: "Route not found"
        }));

    }

});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});

Request Body

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

Expected Response

JSON Response
{
    "message": "Student details updated successfully",
    "student": {
        "id": 2,
        "name": "Pradnya",
        "course": "Node.js"
    }
}

Explanation: Only the supplied course field changes. The ID and name remain unchanged. In this example, the update affects an in-memory object and resets when the server restarts.

9. DELETE Method in Node.js

The DELETE method is used to request removal of a resource. For example, an administrator may want to delete a student record from the system.

Example: DELETE Request

JavaScript
const http = require("node:http");

const server = http.createServer((req, res) => {

    res.setHeader("Content-Type", "application/json; charset=utf-8");

    if (req.method === "DELETE" && req.url === "/students/2") {

        res.writeHead(200);

        res.end(JSON.stringify({
            message: "DELETE request received for student 2"
        }));

    } else {

        res.writeHead(404);

        res.end(JSON.stringify({
            message: "Route not found"
        }));

    }

});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});

Test the Request

Postman
DELETE http://localhost:3000/students/2

Expected Response

JSON Response
{
    "message": "DELETE request received for student 2"
}

Explanation: This example demonstrates how to recognize a DELETE request. It does not actually delete a student because it does not use a database or a stored collection. A real DELETE handler must locate and remove the resource before returning success.

10. Difference Between GET, POST, PUT, PATCH and DELETE

Method Reads Data Sends Body Commonly Main Purpose
GET Yes Usually no Retrieve data.
POST Not its main purpose Often yes Submit data or create a resource.
PUT Not its main purpose Often yes Create or replace a resource.
PATCH Not its main purpose Often yes Partially update a resource.
DELETE Not its main purpose Usually no Delete a resource.

Note: Request bodies are not universally required or forbidden for every method. Follow the API's documented behavior.

11. Request Method Decision Flow

A Node.js server can check the request method and URL and then execute the matching route handler.

Incoming Request

req.method and req.url

↓
Check Method and URL
GET

Read data

POST

Create or submit data

PUT / PATCH

Replace or update data

DELETE

Remove a resource

↓
Send HTTP Response

Appropriate status code, headers and response body

12. How to Run a Node.js HTTP Program

  1. Install Node.js on your computer.
  2. Create a file named server.js.
  3. Copy one example into the file.
  4. Open the terminal in that folder.
  5. Run node server.js.
  6. Send the request using a browser or Postman, depending on the method being tested.

Terminal Command

Terminal
node server.js

Expected Output

Output
Server running on port 3000
Important: Each standalone example creates its own server. Test one example at a time, and stop the previous server before starting another server on the same port.

Important Points

  • req.method identifies the incoming HTTP method.
  • req.url identifies the requested URL.
  • GET is commonly used to retrieve data.
  • POST is commonly used to submit data or create resources.
  • PUT generally replaces a resource, while PATCH updates selected fields.
  • DELETE requests removal of a resource.
  • Validate incoming data and send an appropriate status code.

Summary

In this lesson, we learned how HTTP request methods work in Node.js using the built-in HTTP module. We explored how to identify incoming requests using req.method and req.url, and studied GET, POST, PUT, PATCH and DELETE through practical examples. These methods help clients communicate their intended operations to a server and form an important foundation for building HTTP APIs.