Topics in this subject
Node.js 3 min read Updated 11 Aug 2026

Express.js Basics and Routing

Setting up an Express server, handling HTTP methods, and routing requests.

🧑‍🏫 Sabse pehle — simple mein samjho#

Pure Node.js (http module) se server banana bohot lamba aur complex kaam hai. HTTP requests handle karna, JSON bhejna, URL parameters padhna — ye sab raw Node mein aafat hai. Express.js Node ka sabse famous framework hai jo in sab kaamon ko ekdum simple bana deta hai. Ye essentially Node ke upar ek wrapper hai jo humein saaf sutra (clean) API banane ki taqat deta hai.

Basic Setup#

First, initialize npm and install Express: npm install express.

const express = require('express');
const app = express(); // Initialize the express application
const PORT = 3000;

// A basic GET route
app.get('/', (req, res) => {
    // Express automatically sets the Content-Type to text/html
    res.send('<h1>Hello from Express!</h1>');
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

The Request (req) and Response (res) Objects#

Express enhances the standard Node req/res objects with powerful helper methods.

1. Sending JSON Responses#

Building a REST API means sending JSON data.

app.get('/api/users', (req, res) => {
    const users = [{ id: 1, name: "Tarun" }];
    // res.json() converts the object to a JSON string and sets headers automatically
    res.status(200).json(users); 
});

2. Route Parameters (Dynamic URLs)#

Used to capture specific identifiers from the URL (e.g., getting a single user's ID).

// The colon ':' denotes a dynamic parameter
app.get('/api/users/:id', (req, res) => {
    // Extracted from req.params
    const userId = req.params.id; 
    res.json({ message: `Fetching user with ID: ${userId}` });
});

3. Query Parameters#

Used for filtering, sorting, or pagination (e.g., /api/users?sort=desc&limit=10).

app.get('/api/search', (req, res) => {
    // Extracted from req.query
    const { sort, limit } = req.query;
    res.json({ sortedBy: sort, maxItems: limit });
});

HTTP Methods (RESTful Routing)#

Express provides methods that directly map to HTTP verbs used in REST APIs.

  • app.get(): Fetching data.
  • app.post(): Creating new data (requires parsing the request body).
  • app.put() / app.patch(): Updating existing data.
  • app.delete(): Deleting data.

Parsing incoming Request Bodies#

If a client sends data to your server via a POST request (like a JSON payload from a React frontend), Express needs a built-in middleware to read it.

// MUST add this line before your routes to read JSON data!
app.use(express.json());

app.post('/api/users', (req, res) => {
    // The parsed JSON data is now available in req.body
    const { name, email } = req.body;
    
    console.log("New user:", name);
    res.status(201).json({ message: "User created!" });
});