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
npm install express
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/");
});
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
app.get("/users/:id", (req, res) => {
res.send(`Looking up user ${req.params.id}`);
});
curl http://localhost:3000/users/42
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:
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.
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.