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

Request and Response in Express.js

Learn how to handle HTTP requests and send responses using the request (req) and response (res) objects in Express.js.

Whenever a client sends a request to a server, Express.js provides a request object to read the incoming information and a response object to send the result back to the client. For example, Samadhan requests student details from the CIIT Training Institute server.

Express.js makes it easier to handle requests and responses using methods such as app.get(), res.send(), res.json() and res.status().

1. What Is a Request Object?

A request object, commonly written as req, contains information about the HTTP request received from the client. It helps the server understand what the client is requesting.

For example, when Pradnya opens the student details page, the browser sends a GET request to the server. Express.js provides the req object to access information about that request.

JavaScript
app.get("/student", (req, res) => {
    console.log(req.method);
    console.log(req.url);

    res.send("Student Details");
});

In this example, req.method returns the HTTP method and req.url returns the requested URL. The server then sends a response to the browser.

Remember: The req object contains information received from the client.

2. Important Request Properties

Express.js provides several request properties that help us read information from incoming HTTP requests.

Property Purpose Example
req.method Returns the HTTP request method. GET
req.url Returns the requested URL. /student
req.query Reads query string parameters. ?name=Pradnya
req.params Reads named route parameters. :id
req.headers Provides incoming HTTP request headers. req.headers.host

We will study route parameters in detail in the next lesson.

3. What Is a Response Object?

A response object, commonly written as res, is used by the server to send data back to the client. The response may contain plain text, HTML, JSON data or an HTTP status code.

For example, when Samadhan requests course information, the server can use res.send() to send a message or res.json() to return structured course data.

JavaScript
app.get("/welcome", (req, res) => {
    res.send("Welcome to CIIT Training Institute!");
});

Here, res.send() sends the welcome message to the client when the /welcome route is requested.

Remember: The res object helps the server send a response back to the client.

4. Important Response Methods

Express.js provides different response methods depending on what information the server needs to return.

Method Purpose Example
res.send() Sends a response such as text or HTML. res.send("Hello")
res.json() Sends a JSON response. res.json({ name: "Pradnya" })
res.status() Sets the HTTP response status code. res.status(404)
res.end() Ends the response without sending additional data. res.end()

5. How Do Request and Response Work?

The client sends an HTTP request to the Express.js server. Express matches the route, executes its callback function, processes the request and sends a response to the client.

1. Client / Browser

Samadhan requests student information.

↓
2. HTTP Request

The client sends a GET request to /student.

↓
3. Request Object (req)

Express reads the incoming request information.

↓
4. Response Object (res)

The server sends the requested student information.

↓
5. Client Receives Response

The browser receives the response data.

6. First Program: Handling a Request and Response

Let's create a simple Express.js server that receives a request and sends a text response to the client.

Step 1: Create app.js

JavaScript
const express = require("express");

const app = express();

app.get("/student", (req, res) => {

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

    res.send("Student details received successfully");

});

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

Step 2: Run the Server

Terminal
node app.js

Step 3: Open the URL

URL
http://localhost:3000/student

Expected Terminal Output

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

Expected Browser Response

Response
Student details received successfully

Explanation: The app.get() method defines a GET route. When the client requests /student, Express executes the callback function. The req object provides the method and URL, while res.send() sends the response to the browser.

7. Sending a JSON Response

APIs often return data in JSON format. The res.json() method sends a JavaScript object to the client as a JSON response.

Example: Sending Student Details

JavaScript
const express = require("express");

const app = express();

app.get("/student", (req, res) => {

    const student = {
        id: 1,
        name: "Pradnya",
        course: "Node.js"
    };

    res.json(student);

});

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

Test URL

URL
http://localhost:3000/student

Expected Response

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

Explanation: The server creates a student object and passes it to res.json(). Express serializes the object into JSON and sends it to the client.

8. Sending a Response with a Status Code

HTTP status codes tell the client the result of a request. For example, status code 200 indicates success, 201 indicates that a resource was created, and 404 indicates that a resource was not found.

Example: Page Not Found

JavaScript
const express = require("express");

const app = express();

app.get("/not-found", (req, res) => {

    res.status(404).send("Page not found");

});

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

Test URL

URL
http://localhost:3000/not-found

Expected Response

Response — HTTP 404
Page not found

Explanation: The res.status(404) method sets the status code to 404. The chained send() method sends the error message to the client.

9. Reading Query Parameters from a Request

Query parameters allow clients to send additional information through the URL. They are commonly used for searching and filtering data.

For example, Pradnya can request a greeting by providing her name in the query string.

Example: Reading a Name

JavaScript
const express = require("express");

const app = express();

app.get("/welcome", (req, res) => {

    const name = req.query.name || "Student";

    res.send("Welcome, " + name + "!");

});

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

Test URL

URL
http://localhost:3000/welcome?name=Pradnya

Expected Response

Output
Welcome, Pradnya!

Explanation: The req.query.name property reads the value of the name query parameter. If the parameter is missing, the example uses Student as the default.

10. Difference Between req and res

Request Object (req) Response Object (res)
Contains incoming request information. Used to send a response to the client.
Reads the request method and URL. Sends text, JSON and status codes.
Example: req.method Example: res.send()
Example: req.query Example: res.json()

11. Important Points

  • The req object contains incoming request information.
  • The res object sends a response to the client.
  • Use req.method to read the HTTP method.
  • Use req.url to read the requested URL.
  • Use res.send() to send text or HTML.
  • Use res.json() to send JSON data.
  • Use res.status() to set an HTTP status code.
  • Send only one final response for each request.

Summary

In this lesson, we learned how Express.js handles HTTP requests and responses. We explored the request object and its properties, sent text and JSON responses, used HTTP status codes, and read query parameters. These concepts are essential for building Express.js web applications and REST APIs.