Episode 6 of 12

Express.js Basics

Introduction to Express.js — the most popular Node.js web framework for building clean, fast web applications and APIs.

Express.js is the most popular web framework for Node.js. It simplifies routing, middleware, and request handling — making it much easier to build web applications compared to raw Node.js HTTP module.

Installing Express

npm install express

Creating an Express App

const express = require('express');
const app = express();

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

// Routes
app.get('/', (req, res) => {
    res.send('<h1>Home Page</h1>');
});

app.get('/about', (req, res) => {
    res.send('<h1>About Page</h1>');
});

// 404 - must be at the bottom
app.use((req, res) => {
    res.status(404).send('<h1>404 - Page Not Found</h1>');
});

Why Express?

  • Cleaner syntax — No manual URL parsing or status code setting
  • Built-in routingapp.get(), app.post(), etc.
  • Middleware support — Plug in functionality easily
  • Huge ecosystem — Thousands of middleware packages available

Serving HTML Files

app.get('/', (req, res) => {
    res.sendFile('./views/index.html', { root: __dirname });
});

app.get('/about', (req, res) => {
    res.sendFile('./views/about.html', { root: __dirname });
});

Redirects in Express

app.get('/about-us', (req, res) => {
    res.redirect('/about');
});

Express automatically sets the 301 status code for redirects. Much simpler than raw Node.js!