Course outline · 0% complete

0/29 lessons0%

Course overview →

Express Routing

lesson 5-1 · ~11 min · 14/29

Quiz

Warm-up from lesson 4-1. In a REST API, how do you express the action "create a new order"?

What Express is

Express is the most-used Node web framework, a thin layer over http that does the chores you have been hand-rolling: route matching, params, query parsing, JSON responses. You install it from npm, Node's package registry:

npm install express
const express = require("express");
const app = express();

app.get("/users/:id", (req, res) => {
  res.json({ id: req.params.id, name: "Ada" });
});

app.listen(3000);

Everything here is familiar. app.get("/users/:id", handler) is your routing table from lesson 3-2, :id is your matchPath with captures (req.params.id), the handler is a callback, and res.json sets the JSON header and stringifies for you.

What Express hands you on req

For a request to GET /posts?status=draft&page=2 matched by app.get("/posts", ...):

PropertyValueFilled by
req.params{} (no :segments here)the route pattern
req.query{ status: "draft", page: "2" }the query string
req.bodythe parsed JSON bodyexpress.json() middleware (next lesson)

Note every value is a string. page arrives as "2", not 2.

That req.query object comes from parsing status=draft&page=2: split on &, then split each piece on =. You have written parsers twice already (lessons 1-3 and 3-2). Write this one and you will never wonder what a framework does with query strings again.

Code exercise · javascript

Your turn. Implement parseQuery(qs) turning "status=draft&page=2" into { status: "draft", page: "2" }. An empty string returns {}. Split on "&" first, then each pair on "=".

Code exercise · javascript

Your turn. An Express handler for GET /users/:id receives req.params.id as the STRING "2". Implement getUser(params): convert params.id with Number(...), find the user in the array, and return { status: 200, body: user }, or a 404 with the lesson 4-3 error shape (code "user_not_found") when no user has that id.