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 Requests in Node.js

In Node.js, handling requests means receiving an HTTP request from a client, examining its URL, HTTP method and headers, and deciding how the server should respond.


1. What is Request Handling?

When a browser opens a website, it sends an HTTP request to the server. The server receives that request and processes it using the request handler registered with http.createServer().

For example, Samadhan opens the CIIT Training Institute website. Pradnya's Node.js server receives the request and checks which page Samadhan wants to access before sending the appropriate response.

Simple Trick: Request handling means checking what the client is asking for and deciding what response the server should send.

2. Understanding the Request Object

The request object, usually named req, contains information about the incoming HTTP request.

Property Description Example
req.url Provides the request URL path and query string. /courses
req.method Provides the HTTP method. GET
req.headers Contains the request headers. host, accept
req.headers["content-type"] Reads the content type header when supplied. application/json

3. Displaying Request Information

We can display the URL, HTTP method, and headers of an incoming request using the request object.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    console.log("Request URL:", req.url);
    console.log("Request Method:", req.method);
    console.log("Request Headers:", req.headers);

    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });

    res.end("Request received successfully!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
Terminal Output
Server running at http://localhost:3000
Request URL: /
Request Method: GET
Request Headers: [request header object]
The header object contains actual values supplied by your browser. Additional requests may appear in the terminal.
Browser Output
Request received successfully!
Explanation
  • req.url tells us the requested path.
  • req.method tells us which HTTP method was used.
  • req.headers contains metadata sent by the client.
  • res.end() sends the response and completes the request's response.

4. Request Handling Flow

HTTP Request Processing Diagram
1. Client Sends Request
Samadhan opens a URL in the browser.
↓
2. Server Receives Request
The request handler receives req and res.
↓
3. Inspect Request
Check req.url, req.method and req.headers.
↓
4. Choose the Response
Determine the appropriate page or result.
↓
5. Send HTTP Response
The browser receives the result.

5. Handling Different URLs

A server can respond differently depending on the requested URL. This is a simple form of manual routing using Node.js's built-in HTTP module.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });

    if (req.url === "/") {
        res.end("Welcome to CIIT Training Institute!");
    } else if (req.url === "/courses") {
        res.end("Available courses: Java, Python, .NET and Node.js");
    } else if (req.url === "/about") {
        res.end("Learn more about CIIT Training Institute.");
    } else {
        res.writeHead(404, {
            "Content-Type": "text/plain; charset=utf-8"
        });

        res.end("404 - Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
Important correction for real execution: In the example above, the initial writeHead(200) sends the headers before the 404 branch. For a correct 404 response, set the status inside each route before sending the body. Use the corrected version below.
Corrected Code
JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/plain; charset=utf-8");

    if (req.method !== "GET") {
        res.writeHead(405);
        res.end("405 - Method Not Allowed");
    } else if (req.url === "/") {
        res.writeHead(200);
        res.end("Welcome to CIIT Training Institute!");
    } else if (req.url === "/courses") {
        res.writeHead(200);
        res.end("Available courses: Java, Python, .NET and Node.js");
    } else if (req.url === "/about") {
        res.writeHead(200);
        res.end("Learn more about CIIT Training Institute.");
    } else {
        res.writeHead(404);
        res.end("404 - Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});
Try These URLs
URL Expected Response Status
http://localhost:3000/ Welcome to CIIT Training Institute! 200
http://localhost:3000/courses Available courses: Java, Python, .NET and Node.js 200
http://localhost:3000/about Learn more about CIIT Training Institute. 200
http://localhost:3000/contact 404 - Page Not Found 404

6. Handling Query Strings

A URL may contain query parameters. For example, /student?name=Samadhan contains the path /student and the query parameter name. We can use Node.js's URL class to parse them.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    const requestUrl = new URL(
        req.url,
        "http://localhost:3000"
    );

    if (requestUrl.pathname === "/student") {
        const name = requestUrl.searchParams.get("name") || "Student";

        res.writeHead(200, {
            "Content-Type": "text/plain; charset=utf-8"
        });

        res.end("Welcome, " + name + "!");
    } else {
        res.writeHead(404, {
            "Content-Type": "text/plain; charset=utf-8"
        });

        res.end("Page Not Found");
    }
});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});
Test URL
URL
http://localhost:3000/student?name=Samadhan
Browser Output
Welcome, Samadhan!
Explanation
  • new URL() parses the request URL.
  • pathname gives the path, such as /student.
  • searchParams.get("name") reads the name query parameter.
  • The server uses the name to construct its response.
Security Tip: Treat query parameters as untrusted input. Validate them before using them in database queries, file paths, or other sensitive operations.

7. Handling Different HTTP Methods

The HTTP method indicates the kind of operation the client wants to perform. Common methods include GET, POST, PUT, and DELETE.

Method Typical Purpose
GET Retrieve information.
POST Submit data or create a resource.
PUT Create or replace a resource at a known URI, depending on the API.
DELETE Request removal of a resource.

For this lesson, we will handle GET requests and return a 405 status for other methods.

JavaScript
const http = require("http");

const server = http.createServer((req, res) => {
    res.setHeader("Content-Type", "text/plain; charset=utf-8");

    if (req.method === "GET") {
        res.writeHead(200);
        res.end("GET request received successfully.");
    } else {
        res.writeHead(405);
        res.end("Only GET requests are supported.");
    }
});

server.listen(3000, () => {
    console.log("Server running on port 3000");
});
Expected Response for a GET Request
GET request received successfully.
Expected Response for Another Method
Only GET requests are supported.

8. Common Mistakes

Mistake Correct Approach
Checking only the URL and ignoring the HTTP method. Check both req.url and req.method when needed.
Sending a 200 status for an unknown route. Return 404 when the requested resource is not found.
Comparing a complete URL directly when query strings are present. Parse the URL and compare pathname.
Trying to send another response after res.end(). Send one completed response for each request.
Trusting query parameter values without validation. Validate and safely handle client-provided input.

9. Important Points to Remember

  • req contains information about the incoming request.
  • req.url provides the request URL.
  • req.method provides the HTTP method.
  • req.headers contains request headers.
  • The URL class can parse paths and query parameters.
  • Use appropriate status codes such as 200, 404, and 405.
  • Complete each response with res.end().

Summary

In this lesson, we learned how to inspect incoming HTTP requests, read URL paths and methods, handle different routes, parse query parameters, and return suitable status codes. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how a Node.js server can respond to different client requests.