5️⃣ Introduction to Express.js

The Most Popular Node.js Framework

5.1 Why Express?

Express.js is a minimal, flexible web framework for Node.js. It simplifies building APIs.

Without Express vs With Express

Without Express ❌ With Express ✅
Manual URL parsing Simple routing (app.get())
Complex response handling res.json(), res.send()
No middleware system Built-in middleware support
Lots of boilerplate Clean, minimal code
DIY error handling Structured error handling

Express is the Industry Standard

5.2 Setting up Express

Step 1: Create Project Folder

# Create and enter project folder
mkdir my-api
cd my-api

Step 2: Initialize npm

# Create package.json
npm init -y

This creates package.json:

{
  "name": "my-api",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  }
}

Step 3: Install Express

npm install express

Step 4: Create Basic Server

Create index.js:

// index.js - Basic Express server
const express = require('express');
const app = express();

// Middleware to parse JSON body
app.use(express.json());

// Basic route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

// JSON route
app.get('/api', (req, res) => {
  res.json({ message: 'Welcome to our API!' });
});

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

Step 5: Run the Server

node index.js
# Server running at http://localhost:3000

Visit http://localhost:3000 in your browser!

🎉 You just created your first Express server!

5.3 Routing

Routes define how your API responds to different URLs and HTTP methods.

HTTP Methods

// routes.js - Full CRUD example
const express = require('express');
const app = express();
app.use(express.json());

// In-memory data (replace with database later)
let products = [
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Phone', price: 699 }
];

// GET - Read all products
app.get('/products', (req, res) => {
  res.json(products);
});

// GET - Read one product by ID
app.get('/products/:id', (req, res) => {
  const product = products.find(p => p.id === parseInt(req.params.id));
  
  if (!product) {
    return res.status(404).json({ error: 'Product not found' });
  }
  
  res.json(product);
});

// POST - Create a new product
app.post('/products', (req, res) => {
  const newProduct = {
    id: products.length + 1,
    name: req.body.name,
    price: req.body.price
  };
  
  products.push(newProduct);
  res.status(201).json(newProduct);
});

// PUT - Update a product
app.put('/products/:id', (req, res) => {
  const product = products.find(p => p.id === parseInt(req.params.id));
  
  if (!product) {
    return res.status(404).json({ error: 'Product not found' });
  }
  
  product.name = req.body.name || product.name;
  product.price = req.body.price || product.price;
  
  res.json(product);
});

// DELETE - Remove a product
app.delete('/products/:id', (req, res) => {
  const index = products.findIndex(p => p.id === parseInt(req.params.id));
  
  if (index === -1) {
    return res.status(404).json({ error: 'Product not found' });
  }
  
  products.splice(index, 1);
  res.json({ message: 'Product deleted' });
});

app.listen(3000, () => console.log('Server on port 3000'));

URL Parameters

Parameters are parts of the URL path:

// URL: /users/42
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;  // "42"
  res.json({ userId });
});

// URL: /products/electronics/laptops
app.get('/products/:category/:type', (req, res) => {
  const { category, type } = req.params;
  // category = "electronics", type = "laptops"
  res.json({ category, type });
});

Query Parameters

Query parameters come after ? in the URL:

// URL: /search?q=laptop&sort=price&limit=10
app.get('/search', (req, res) => {
  const query = req.query.q;       // "laptop"
  const sort = req.query.sort;     // "price"
  const limit = req.query.limit;   // "10" (string!)
  
  res.json({ 
    searchQuery: query,
    sortBy: sort,
    limit: parseInt(limit) || 10
  });
});

// URL: /products?category=phones&minPrice=500
app.get('/products', (req, res) => {
  let filtered = products;
  
  if (req.query.category) {
    filtered = filtered.filter(p => p.category === req.query.category);
  }
  
  if (req.query.minPrice) {
    filtered = filtered.filter(p => p.price >= parseInt(req.query.minPrice));
  }
  
  res.json(filtered);
});
💡 URL Params vs Query Params:
  • URL Params (/users/:id) - Required, identifies a specific resource
  • Query Params (?sort=price) - Optional, filters or modifies the response

5.4 async/await in Express Routes

Most real routes need to do async operations (database, external APIs).

The Standard Pattern ⭐

// async-routes.js
const express = require('express');
const app = express();
app.use(express.json());

// Simulate database function
function findUserById(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const users = [
        { id: 1, name: 'Alice', email: 'alice@mail.com' },
        { id: 2, name: 'Bob', email: 'bob@mail.com' }
      ];
      const user = users.find(u => u.id === id);
      
      if (user) {
        resolve(user);
      } else {
        reject(new Error('User not found'));
      }
    }, 500);
  });
}

// ✅ Async route with try/catch
app.get('/users/:id', async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const user = await findUserById(userId);
    res.json(user);
  } catch (error) {
    res.status(404).json({ error: error.message });
  }
});

// ✅ POST with validation
app.post('/users', async (req, res) => {
  try {
    const { name, email } = req.body;
    
    // Validation
    if (!name || !email) {
      return res.status(400).json({ 
        error: 'Name and email are required' 
      });
    }
    
    // Create user (would save to DB)
    const newUser = { id: Date.now(), name, email };
    
    res.status(201).json(newUser);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

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

HTTP Status Codes

Code Meaning When to Use
200 OK Successful GET, PUT
201 Created Successful POST (new resource)
400 Bad Request Invalid data sent by client
401 Unauthorized Not logged in
404 Not Found Resource doesn't exist
500 Server Error Something broke on server

Testing Your API

Use these tools to test your API:

1. Browser (GET only)

Just visit http://localhost:3000/products

2. PowerShell (Windows Command Line)

# GET request
Invoke-RestMethod -Uri http://localhost:3000/products -Method Get

# POST request
$body = @{
    name = "Tablet"
    price = 499
} | ConvertTo-Json

Invoke-RestMethod -Uri http://localhost:3000/products -Method Post -Body $body -ContentType "application/json"

# PUT request
$body = @{
    price = 899
} | ConvertTo-Json

Invoke-RestMethod -Uri http://localhost:3000/products/1 -Method Put -Body $body -ContentType "application/json"

# DELETE request
Invoke-RestMethod -Uri http://localhost:3000/products/1 -Method Delete
💡 PowerShell Notes:
  • Invoke-RestMethod is the PowerShell command for HTTP requests
  • Use -Method to specify GET, POST, PUT, DELETE
  • Create a hash table with @{}, then convert to JSON
  • PowerShell automatically displays JSON responses in a readable format

3. VS Code Extension: REST Client

Create a file test.http:

### Get all products
GET http://localhost:3000/products

### Get one product
GET http://localhost:3000/products/1

### Create product
POST http://localhost:3000/products
Content-Type: application/json

{
  "name": "Tablet",
  "price": 499
}

### Delete product
DELETE http://localhost:3000/products/1
🎯 Key Takeaways:
  • Express simplifies Node.js web development
  • Use app.get/post/put/delete() for routing
  • req.params for URL parameters (/users/:id)
  • req.query for query strings (?sort=price)
  • req.body for POST/PUT data
  • Always use async/await with try/catch
  • Return appropriate HTTP status codes