Intro to Express

The raw http module from earlier works, but routing by hand-checking req.url strings gets unwieldy fast. Express is a thin, extremely popular framework built directly on top of http that adds real routing and a lot of convenience.

A minimal Express server

bash terminal
npm install express
JS server.js
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("Welcome to the homepage.");
});

app.listen(3000, () => {
  console.log("Server running at http://localhost:3000/");
});
Output
Server running at http://localhost:3000/

Compare this to lesson 4's raw http version: app.get(path, handler) replaces manually checking req.url === "/", and res.send() replaces res.end() — it's smart enough to set the right headers for a string, an object (auto-converted to JSON), or a buffer.

Routes with parameters

JS server.js
app.get("/users/:id", (req, res) => {
  res.send(`Looking up user ${req.params.id}`);
});
bash terminal
curl http://localhost:3000/users/42
Output
Looking up user 42

The :id segment becomes a named parameter, available on req.params.id — no manual URL parsing required.

Middleware

Middleware functions run before your route handler, and can read/modify the request, end the response early, or call next() to pass control along:

JS server.js
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.use(express.json());

app.get("/", (req, res) => res.send("Home"));

express.json() is built-in middleware that parses a JSON request body into req.body automatically — without it, req.body would be undefined on a POST request with a JSON payload.

Note: middleware and routes run in the exact order they're registered with app.use()/app.get()/etc. Registering express.json() after a route that needs req.body means that route sees undefined — order isn't a style preference here, it's functional.