T9 APIs · Lesson 3
Express routing
Express is the router that almost every Node API is built on: a package that reads the verb and the path of each request and calls the function you gave for that pair. Write your first app, add a route for each verb and path, read names out of a path and the query string, send every kind of answer, and group routes in routers.
- install Express and write an app that answers one address
- add a route for each verb and path, and say what Express answers when none matches
- read names out of a path with route parameters, wildcards and optional parts
- read the query string, the headers and the other facts of a request
- send text, JSON, a status, a redirect or nothing at all, with the headers Express adds
- group routes in a Router and mount it at one address
The back cover
A railway yard has one switchman who reads each wagon's label and sends it down the right track. Without him, every wagon would end up on the same line. He works fast, and he never sends one wagon down two tracks.
These pages show Express, the switchman of most Node APIs. They write a first app, add routes for each verb and path, read names inside the path and the query string, send every kind of answer, and group routes into routers, each in a file of its own. One small file can then answer a whole API.
Before you start
The story: The sorting machine
The yard has grown. Parcels for the gauges, the readings, the halls and the couriers themselves pile up at one door, and the three sorters read every label by hand. By noon the queue reaches the gate.
Yardmaster Waybill rolls back a tarpaulin. Under it stands a long belt with a row of benches beside it. "A sorting machine," she says. "You tell it once which verb and which address go to which bench, and it sends every parcel to the right one. A parcel for an address it does not know goes back, stamped."
"Learn to set its benches," she says, "and the queue is gone by lunch."
In lesson 01 you wrote an API on Node's own http module: one function read the verb and the path of every request and worked out what to do. That was fine for three addresses. An API with thirty addresses needs a router: a part that reads the verb and the path for you, and calls the right function for each pair.
Express is that router, and a little more. It is a package from npm that sits on top of Node's http module. You tell it which function answers which verb and path, and it does the reading, the matching and the plain parts of every answer.
This lesson is about Express's routing: the first app, routes for each verb, names inside a path, the query string, how an answer is sent, and routers that group routes together. The checkpoints along the way, which Express calls middleware, are the next lesson.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| A server and its client. | http.createServer | Express builds on it. |
| req.method and req.url. | req.method === "GET" | What a route matches. |
| HTTP verbs. | GET, POST, PUT, PATCH, DELETE | One method of app for each. |
| Status codes. | 200, 201, 404 | res.status and the 404 page. |
| Headers. | Content-Type | What Express adds for you. |
| JSON. | JSON.stringify(data) | res.json does it. |
| require and modules. | require("./gauges") | A router in a file of its own. |
| npm packages. | npm install ms | Installing Express. |
| Arrow functions. | (req, res) => res.send(1) | Every handler is one. |
| async and await. | await fetch(url) | The client in each block. |
By the end of this lesson you will be able to:
- install Express and write an app that answers one address;
- add a route for each verb and path, and say what Express answers when none matches;
- read names out of a path with route parameters, wildcards and optional parts;
- read the query string, the headers and the other facts of a request;
- send text, JSON, a status, a redirect or nothing at all, with the headers Express adds;
- group routes in a Router and mount it at one address.
How to follow this lesson
Every block is a program that starts an Express app, sends it a few requests with fetch, prints what came back, and closes the server. It runs on the page in the small Node, whose Express is a small one written for it, and it has also been run with the real Express 5.3.0 in real Node 22, where it prints the same.
A block prints chosen headers and never the Date header, which changes with the clock.
In one line
Express is a router on top of Node's http module: you say which function answers which verb and path, and it does the reading, the matching and the plain parts of every answer.
The first app
At a glance
Express is the router that almost every Node API is built on. It reads the verb and the path of each request and calls the function you gave for that pair.
Three calls make an app. The call express() makes it, app.get(path, handler) adds a route, and app.listen(port) starts a Node server underneath. Inside a handler, res.send answers with a body, and Express adds the headers that the answer needs, such as its type and length. An address that no route matches gets a 404 page of its own.
Take a guess: How long did the Express team take to finish Express 5?
Express comes from npm, like the packages of the Node track. In the shop's folder, one install brings it and the packages it is built from:
Measured in a real terminal on 2026-11-15, with Node 22.23.1 and npm 10.9.8
asha@tower:~/shop$ npm install express
added 65 packages, and audited 66 packages in 16s
30 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
asha@tower:~/shop$ grep version node_modules/express/package.json
"version": "5.3.0",
Sixty-five packages for one router sounds like a lot. Express is built from small packages that each do one thing, such as matching a path or sending a file, and npm brings them all. The shop's package.json now lists express as a dependency, as the Node track showed.
The blocks on this page skip the install: the page's small Node holds a small Express of its own, and the kit's sandbox holds the real one, so require("express") works in both.
Three lines and a route
The smallest Express app has three parts: express() makes the app, a route says which function answers a verb and a path, and app.listen starts the server. Here is the whole of it, with a client that asks for the front door:
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("hello from the yard");
});
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/");
console.log(r.status, r.statusText, await r.text());
server.close();
});
Terminal: node app.js
200 OK hello from the yard
Read it line by line. require("express") gives a function; calling it gives an app, the object that holds every route. app.get("/", handler) adds a route: the verb is GET, the path is /, and the handler is the function that answers.
A handler gets two arguments, as in Node's http module: the request and the response. res.send sends the body and ends the response in one call. Then app.listen(3000, callback) starts a server on port 3000 and calls the callback once it listens, as server.listen did in the Node track.
Compare the same app on Node's http module alone. It had to read the verb and the path itself, write the head itself, and answer every other request itself:
app.js
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
return res.end("hello from the yard");
}
res.writeHead(404);
res.end();
});
server.listen(3000, async () => {
const r = await fetch("http://localhost:3000/");
console.log(r.status, r.statusText, await r.text());
server.close();
});
Terminal: node app.js
200 OK hello from the yard
Both print the same line. The difference is the work: Express read the verb and the path, matched them to the route, set the head, and answered the unknown addresses, all without a line from you.
What Express added
A response from Express carries headers that you did not set. The client here prints four of them:
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("hello from the yard"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/");
for (const name of ["x-powered-by", "content-type", "content-length", "etag"]) {
console.log(name + ": " + r.headers.get(name));
}
server.close();
});
Terminal: node app.js
x-powered-by: Express
content-type: text/html; charset=utf-8
content-length: 19
etag: W/"13-UhVbH3EdBgxS6LizNsr5HD+siyU"
| Header | Value | Why Express adds it |
|---|---|---|
X-Powered-By | Express | a signature; app.disable("x-powered-by") removes it |
Content-Type | text/html; charset=utf-8 | a string sent by res.send counts as HTML unless you set a type |
Content-Length | 19 | the body's size in bytes, counted for you |
ETag | W/"13-UhVb..." | a fingerprint of the body, for caching: a client that holds it can ask whether the body changed |
The ETag is a weak one: W, then the body's length in hexadecimal, then part of a hash of the body. Every answer with the same body gets the same ETag, and a changed body gets a new one. Caching with it is a later lesson; for now, know where the header comes from.
An address nobody answers
Ask Express for an address that has no route, and it answers by itself. The client prints the status, the type and the whole body:
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("hello from the yard"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/nowhere");
console.log(r.status, r.statusText, r.headers.get("content-type"));
console.log((await r.text()).trimEnd());
server.close();
});
Terminal: node app.js
404 Not Found text/html; charset=utf-8
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /nowhere</pre>
</body>
</html>
The status is 404, the body is a small HTML page, and its one line says what was asked: the verb and the path. A browser shows that page; a program reads the status. Any verb gets the same treatment: a POST to / with no POST route answers Cannot POST /.
The server underneath
app.listen returns the same kind of server that http.createServer returns, because that is what Express makes underneath. So everything from the Node track still applies: server.close, server.address and server.listening. And a HEAD request is answered by the GET route, with the same headers and no body:
app.js
const express = require("express");
const http = require("http");
const app = express();
app.get("/", (req, res) => res.send("hello from the yard"));
const server = app.listen(3000, async () => {
console.log(server instanceof http.Server, server.listening, server.address().port);
const r = await fetch("http://localhost:3000/", { method: "HEAD" });
console.log(r.status, r.headers.get("content-length"), JSON.stringify(await r.text()));
server.close(() => console.log("closed", server.listening));
});
Terminal: node app.js
true true 3000
200 19 ""
closed false
Worked example 1
Write an app that answers the front door and /about, and show what a third address gets.
What we have: two routes to write, and a client that asks for three paths
What we need: one line per path: the path, the status, and the body, or the one line of the 404 page
The plan: add app.get for / and /about; in the client, loop over the three paths; for a 404 page, keep only the text between the pre tags
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("the yard's front door"));
app.get("/about", (req, res) => res.send("the yard sorts parcels for every hall"));
const server = app.listen(3000, async () => {
for (const path of ["/", "/about", "/help"]) {
const r = await fetch("http://localhost:3000" + path);
const body = await r.text();
console.log(path, r.status, body.replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/ 200 the yard's front door
/about 200 the yard sorts parcels for every hall
/help 404 Cannot GET /help
- Each route is one call of app.get with its path and its handler.
- The client's loop sends three requests in turn, with await, so the lines come out in order.
- The replace keeps the text between the pre tags of the 404 page and leaves any other body as it is.
The front door and /about answer 200 with their text, and /help answers 404 with Cannot GET /help.
Check: Three paths, three lines; the two routes answered and Express answered the third.
Another way: answer /help yourself with a third route, so that the client never meets the 404 page.
A path that fails: writing app.get("about", ...) without the leading slash. Express paths start with a slash; the route would never match /about.
When you are stuck: Cannot GET /, or the wrong page answers
Does the route's verb match? A browser's address bar sends GET; a form sends POST; fetch sends GET unless you set method.
Does the path match, with its leading slash and the same spelling? A route for /gauges does not answer /gauge.
Is the client asking the port you listened on? app.listen(3000) answers at http://localhost:3000 and nowhere else.
Your turn
Which three calls make the smallest Express app?Tap to reveal
- One makes the app, one adds a route, one starts the server.
express(), app.get(path, handler) and app.listen(port).
A client sends POST / to the app above, which has only app.get for /. What comes back?Tap to reveal
- No route matches that verb and path, so Express answers by itself.
404, with the page that says Cannot POST /.
cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("front door"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/", { method: "HEAD" });
console.log(r.status, JSON.stringify(await r.text()));
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
200 ""
- A HEAD request is answered by the GET route.
- A HEAD answer has the headers of the GET answer and no body.
It prints 200 "": the status of the GET route and an empty body.
Did you know?
Ten years to Express 5
Express 5 took ten years. The Express blog of October 15, 2024 says that its release pull request was opened in July 2014, and only then merged and published. It thanks Doug Wilson above all, who spent those ten years keeping Express the most stable project around. Express 4 had come out in April 2014, so it served for a decade.
Why it fits here: It answers this topic's question: Express 5 was opened in July 2014 and published in 2024, ten years later.
Sources: Express blog: Introducing Express v5; npm registry: express
Inspired by Sinatra
Express has been around since 2010. Its version 1.0.0 was tagged by TJ Holowaychuk in November 2010, and its early npm entries describe it as a Sinatra inspired web development framework. Sinatra is a small web framework written in Ruby. From it, Wikipedia says, Express took a design that stays minimal, with many features available as plugins.
Why it fits here: It dates this topic's Express: version 1.0.0 came in 2010, modelled on Ruby's small framework Sinatra.
Sources: GitHub: Express release 1.0.0; npm registry: express 1.0.0; Wikipedia: Express.js; Wikipedia: Sinatra (software)
In one line
express() makes an app, app.get(path, handler) adds a route, and app.listen(port) starts a Node server underneath; res.send answers with a body, Express adds the headers, and any unmatched address gets its 404 page.
Routes: a verb and a path
At a glance
A route in Express is a verb and a path, with a function that answers them.
The methods app.get, app.post, app.put, app.patch and app.delete each add a route for one verb, and app.all adds one for every verb. A HEAD request is answered by the GET route, and an OPTIONS request by the router itself. When several routes could answer, the first one that matches both the verb and the path wins. A string path ignores capitals, a slash at the end and the query string.
Take a guess: Has HTTP gained a new method in recent years?
A route is a verb, a path and a handler. The app has one method for each verb, named after it in lower case: app.get, app.post, app.put, app.patch and app.delete. Each takes the path first and the handler after it.
One path can have several routes, one per verb. The sorting machine reads both the verb and the path, and a request matches a route only when both agree:
app.js
const express = require("express");
const app = express();
const gauges = { boiler: 95, pump: 40 };
app.get("/gauges", (req, res) => res.json(gauges));
app.post("/gauges", (req, res) => res.status(201).send("a gauge would be added here"));
app.delete("/gauges", (req, res) => res.status(204).end());
app.all("/anything", (req, res) => res.send(`${req.method} reached the bench`));
const server = app.listen(3000, async () => {
const asks = [["GET", "/gauges"], ["POST", "/gauges"], ["DELETE", "/gauges"], ["PUT", "/gauges"], ["PATCH", "/anything"], ["HEAD", "/gauges"]];
for (const [method, path] of asks) {
const r = await fetch("http://localhost:3000" + path, { method });
const body = (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, "");
console.log(method, path, r.status, JSON.stringify(body));
}
server.close();
});
Terminal: node app.js
GET /gauges 200 "{\"boiler\":95,\"pump\":40}"
POST /gauges 201 "a gauge would be added here"
DELETE /gauges 204 ""
PUT /gauges 404 "Cannot PUT /gauges"
PATCH /anything 200 "PATCH reached the bench"
HEAD /gauges 200 ""
Three routes share the path /gauges, one per verb, and each sends its own answer. The PUT has no route, so Express answers 404 with Cannot PUT /gauges. app.all takes a path and answers it for every verb; the PATCH to /anything reached it.
The last line is a rule to remember: a HEAD request is answered by the GET route, with the GET answer's headers and no body. You never write a HEAD route.
The answer Express gives for OPTIONS
An OPTIONS request asks which verbs an address takes. When no route of your own answers it, Express's router answers for you, with an Allow header that lists the verbs of the routes at that path:
app.js
const express = require("express");
const app = express();
app.get("/gauges", (req, res) => res.send("the list"));
app.post("/gauges", (req, res) => res.send("added"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges", { method: "OPTIONS" });
console.log(r.status, r.headers.get("allow"), JSON.stringify(await r.text()));
server.close();
});
Terminal: node app.js
200 GET, HEAD, POST "GET, HEAD, POST"
The list holds GET and POST, which you wrote, and HEAD, which the GET route answers. The same list is the body.
First match wins
Routes are checked in the order you wrote them, and the first one that matches the verb and the path answers. The others never see the request:
app.js
const express = require("express");
const app = express();
app.get("/gauges", (req, res) => res.send("the first bench"));
app.get("/gauges", (req, res) => res.send("the second bench"));
app.get("/gauges", (req, res) => res.send("the third bench"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges");
console.log(await r.text());
server.close();
});
Terminal: node app.js
the first bench
Three routes for GET /gauges, and only the first bench answered. The order matters more when paths overlap, which the next section shows; here it means that a catch-all route must come last.
What a string path matches
A path written as a string matches the request's path by its characters, with a few kindnesses. Capital letters do not matter, a trailing slash does not matter, and the query string, from the question mark on, is not part of the path at all. The dot and the hyphen mean themselves:
app.js
const express = require("express");
const app = express();
app.get("/about", (req, res) => res.send("about"));
app.get("/random.text", (req, res) => res.send("a dot"));
app.get("/two-words", (req, res) => res.send("a hyphen"));
const server = app.listen(3000, async () => {
const paths = ["/about", "/About", "/about/", "/about?x=1", "/about/us", "/random.text", "/randomXtext", "/two-words"];
for (const path of paths) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status);
}
server.close();
});
Terminal: node app.js
/about 200
/About 200
/about/ 200
/about?x=1 200
/about/us 404
/random.text 200
/randomXtext 404
/two-words 200
| Request path | Route /about | Why |
|---|---|---|
| /About | matches | letters are compared without regard to case |
| /about/ | matches | a trailing slash is allowed |
| /about?x=1 | matches | the query string is not part of the path |
| /about/us | no match | a longer path is a different address |
Some characters are kept for the patterns of the next section, and a string path may not hold them as plain characters: the question mark, the plus, the parentheses, the square brackets and the exclamation mark. Express refuses such a path the moment you define it, before any request:
app.js
const express = require("express");
const app = express();
for (const path of ["/a+b", "/a(b)", "/a?", "/a-b.c"]) {
try {
app.get(path, (req, res) => res.send("fine"));
console.log(path, "accepted");
} catch (e) {
console.log(path, e.name + ": " + e.message);
}
}
Terminal: node app.js
/a+b TypeError: Unexpected + at index 2: /a+b; visit https://git.new/pathToRegexpError for info
/a(b) TypeError: Unexpected ( at index 2: /a(b); visit https://git.new/pathToRegexpError for info
/a? TypeError: Unexpected ? at index 2: /a?; visit https://git.new/pathToRegexpError for info
/a-b.c accepted
The TypeError names the character and its position, and the link explains. A hyphen and a dot are fine, as the last line shows. Should a path need a plus sign, write it as \\+ in the string, with the backslash escaped for JavaScript.
Worked example 2
The yard's gauges take GET and POST. Make every other verb get a 405 that names the verbs allowed, instead of Express's 404.
What we have: two routes, GET and POST on /gauges, and the rule that the first matching route answers
What we need: an answer with status 405 Method Not Allowed, an Allow header and a JSON body, for PUT, DELETE and the rest
The plan: add app.all for /gauges after the two routes, so that it answers only the verbs those two did not take; in it, set the status, the Allow header and the body
app.js
const express = require("express");
const app = express();
const gauges = { boiler: 95, pump: 40 };
app.get("/gauges", (req, res) => res.json(gauges));
app.post("/gauges", (req, res) => res.status(201).json({ added: true }));
app.all("/gauges", (req, res) => {
res.status(405).set("Allow", "GET, POST").json({ error: `${req.method} is not allowed here; use GET or POST` });
});
const server = app.listen(3000, async () => {
for (const method of ["GET", "PUT", "DELETE", "POST"]) {
const r = await fetch("http://localhost:3000/gauges", { method });
console.log(method, r.status, r.headers.get("allow"), await r.text());
}
server.close();
});
Terminal: node app.js
GET 200 null {"boiler":95,"pump":40}
PUT 405 GET, POST {"error":"PUT is not allowed here; use GET or POST"}
DELETE 405 GET, POST {"error":"DELETE is not allowed here; use GET or POST"}
POST 201 null {"added":true}
- GET and POST match their own routes first, so they never reach the app.all route.
- PUT and DELETE match no earlier route and fall through to app.all, which answers 405.
res.status(405).set("Allow", "GET, POST").json(...)chains three calls: the status, a header, and the body, in one line.- The GET and POST answers have no Allow header, so the client prints null for them.
GET answers 200 and POST 201 as before; PUT and DELETE answer 405 with Allow: GET, POST and a JSON error that names the verb.
Check: Four verbs, four lines: the two routes of the resource, and the catch-all behind them for the rest.
Another way: read req.method inside one app.all handler and branch on it. That works, but it puts the whole resource in one function, which Express's routes were made to avoid.
A path that fails: putting app.all before the two routes. First match wins, so every verb, GET and POST included, would get the 405.
When you are stuck: A route is there and still Cannot GET
Is the verb right? app.post answers only POST; a browser's address bar sends GET.
Is the path the whole path? A route for /gauges does not answer /gauges/boiler; the next section reads such names.
Is a catch-all route above it? Routes are checked in order, and the first match answers, so app.all("/{*splat}") near the top swallows everything.
Your turn
The app has app.get("/gauges") and app.post("/gauges"). What does DELETE /gauges get?Tap to reveal
- No route takes that verb at that path.
404, with the page Cannot DELETE /gauges.
The app has app.get("/about"). What do /About and /about/ get?Tap to reveal
- Letters are compared without regard to case, and a trailing slash is allowed.
Both get 200 from the same route.
cat > app.js <<'END'
const express = require("express");
const app = express();
app.all("/gauges", (req, res) => res.send("all"));
app.get("/gauges", (req, res) => res.send("get"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges");
console.log(await r.text());
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
all
- Routes are checked in the order they were written.
- app.all matches GET too, and it comes first, so it answers.
It prints all: the first matching route answers, and app.all matches every verb.
Did you know?
QUERY, the newest method
HTTP gained a method in June 2026. RFC 10008 defines QUERY: like POST, it carries content, such as a search, but like GET it is safe and idempotent, so it can be repeated or restarted without any harm. Express's documentation already gives app.query an entry of its own, beside app.get, app.post, app.put and app.delete.
Why it fits here: It answers this topic's question: QUERY, from RFC 10008 of June 2026, is a safe search that carries a body.
Sources: IETF Datatracker: The HTTP QUERY Method; RFC 10008: The HTTP QUERY Method; Express 5.x API: Application
Two settings make paths strict
Express can be made strict about paths. Its documentation lists two settings that are off unless set. With case sensitive routing, /Foo and /foo are different routes; with strict routing, /foo and /foo/ are different. Each is read when the app first creates its router, which adding a route already does, so it must be set before any route.
Why it fits here: It adds to this topic's string paths: two settings make capitals and a final slash count, if set before the first route.
In one line
app.get, app.post, app.put, app.patch and app.delete add a route for one verb, and app.all for every verb. HEAD is answered by GET and OPTIONS by the router. The first route that matches both the verb and the path answers, and a string path ignores case, a trailing slash and the query string.
Names inside the path
At a glance
A path can hold names, so that one route answers many addresses.
A colon makes a route parameter, such as /gauges/:name, which matches one segment and puts it in req.params as a decoded string. An asterisk makes a wildcard that takes the rest of the path as an array, and braces make a part optional. A route can have more than one handler: next() goes on to the next handler, and next("route") skips to the next route. A regular expression can be a path too, with its captures numbered.
Take a guess: Why did Express 5 stop allowing a pattern inside a string path?
Most addresses carry a name: /gauges/boiler is the gauge called boiler, and /halls/engine/gauges/pump is one gauge of one hall. A route cannot list every name. Instead it marks the place where a name goes, and Express reads the name out for you.
A route parameter is a segment of the path written as a colon and a name, such as :name. Whatever stands in that segment of the request's path lands in req.params under that name:
app.js
const express = require("express");
const app = express();
const gauges = { boiler: 95, pump: 40 };
app.get("/gauges/:name", (req, res) => {
if (!Object.hasOwn(gauges, req.params.name)) return res.status(404).json({ error: `no gauge called ${req.params.name}` });
res.json({ name: req.params.name, value: gauges[req.params.name] });
});
app.get("/halls/:hall/gauges/:name", (req, res) => res.json(req.params));
const server = app.listen(3000, async () => {
for (const path of ["/gauges/boiler", "/gauges/fan", "/halls/engine/gauges/pump", "/gauges/boiler/extra"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/gauges/boiler 200 {"name":"boiler","value":95}
/gauges/fan 404 {"error":"no gauge called fan"}
/halls/engine/gauges/pump 200 {"hall":"engine","name":"pump"}
/gauges/boiler/extra 404 Cannot GET /gauges/boiler/extra
The first route has one parameter, and the handler uses it to look the gauge up; a name with no gauge gets a 404 of the handler's own, in JSON. Object.hasOwn(gauges, name) asks whether the object itself holds that name; a plain lookup would also find names that every object inherits, such as toString. The second route has two parameters, and req.params holds both. A parameter stands for exactly one segment: /gauges/boiler/extra has a segment too many, so no route matched.
A parameter is a string
Whatever the segment held, req.params gives it as a string, with any percent-codes decoded. A number in the path is still a string, and the handler converts it. The dot and the hyphen mean themselves, so a segment can hold two parameters with one of them between:
app.js
const express = require("express");
const app = express();
app.get("/readings/:n", (req, res) => res.json({ raw: req.params.n, type: typeof req.params.n, number: Number(req.params.n) }));
app.get("/gauges/:name", (req, res) => res.json(req.params));
app.get("/flights/:from-:to", (req, res) => res.json(req.params));
app.get("/plants/:genus.:species", (req, res) => res.json(req.params));
const server = app.listen(3000, async () => {
for (const path of ["/readings/7", "/readings/seven", "/gauges/boiler%20two", "/flights/BOM-DEL", "/plants/Prunus.persica"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, await r.text());
}
server.close();
});
Terminal: node app.js
/readings/7 {"raw":"7","type":"string","number":7}
/readings/seven {"raw":"seven","type":"string","number":null}
/gauges/boiler%20two {"name":"boiler two"}
/flights/BOM-DEL {"from":"BOM","to":"DEL"}
/plants/Prunus.persica {"genus":"Prunus","species":"persica"}
typeof req.params.n is string for /readings/7, and Number turns it into 7; for seven it gives NaN, which JSON writes as null. The space in boiler%20two was decoded. The flights route split BOM-DEL at the hyphen, and the plants route split Prunus.persica at the dot.
Wildcards: the rest of the path
A wildcard is an asterisk and a name, such as *filepath. It matches everything from its place to the end of the path, across any number of slashes, and gives the segments as an array:
app.js
const express = require("express");
const app = express();
app.get("/files/*filepath", (req, res) => res.json({ parts: req.params.filepath, path: req.params.filepath.join("/") }));
app.get("/{*splat}", (req, res) => res.status(404).json({ error: "no such address", parts: req.params.splat ?? [] }));
const server = app.listen(3000, async () => {
for (const path of ["/files/images/logo.png", "/files/notes.txt", "/", "/gauges/x"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/files/images/logo.png 200 {"parts":["images","logo.png"],"path":"images/logo.png"}
/files/notes.txt 200 {"parts":["notes.txt"],"path":"notes.txt"}
/ 404 {"error":"no such address","parts":[]}
/gauges/x 404 {"error":"no such address","parts":["gauges","x"]}
The files route got the two segments of images/logo.png as an array, and join put the slash back. The second route is a catch-all: /{*splat} matches every path, including / itself, where the wildcard is left out of req.params and the handler falls back to an empty array. A catch-all written last turns Express's 404 page into a JSON answer of your own.
Optional segments
Braces make a part of the path optional. Everything inside the braces may be there or not, so the place of the slash matters: /orders{/:id} takes /orders and /orders/42, while /users/{:id} takes /users/ and /users/7 but not /users. When the part is absent, its parameter is left out of req.params:
app.js
const express = require("express");
const app = express();
app.get("/orders{/:id}", (req, res) => res.json({ orders: req.params }));
app.get("/users/{:id}", (req, res) => res.json({ users: req.params }));
app.get("/:file{.:ext}", (req, res) => res.json({ file: req.params }));
const server = app.listen(3000, async () => {
for (const path of ["/orders", "/orders/42", "/users/", "/users/7", "/users", "/image.png", "/image"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/orders 200 {"orders":{}}
/orders/42 200 {"orders":{"id":"42"}}
/users/ 200 {"users":{}}
/users/7 200 {"users":{"id":"7"}}
/users 200 {"file":{"file":"users"}}
/image.png 200 {"file":{"file":"image","ext":"png"}}
/image 200 {"file":{"file":"image"}}
The last route reads a file name with an optional extension after a dot: /image.png gives both parts, /image gives the name alone. And /users, with no slash, reached that route too, as a file called users, because the users route needed the slash.
More than one handler
A route can take several handlers, one after another, as the next lesson's middleware will. Each gets a third argument, next: calling it hands the request to the next handler of the route. Calling next("route") skips the rest of this route and goes on to the next route that matches:
app.js
const express = require("express");
const app = express();
app.get("/users/:id", (req, res, next) => {
if (req.params.id === "0") return next("route");
res.send(`User ${req.params.id}`);
});
app.get("/users/:id", (req, res) => res.send("the special one, user 0"));
app.get("/example", (req, res, next) => {
console.log("the first handler checks, then calls next()");
next();
}, (req, res) => res.send("the second handler answered"));
const server = app.listen(3000, async () => {
for (const path of ["/users/5", "/users/0", "/example"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/users/5 200 User 5
/users/0 200 the special one, user 0
the first handler checks, then calls next()
/example 200 the second handler answered
User 5 was answered by the first route. User 0 made that route call next("route"), so the second route for the same path answered. The /example route has two handlers: the first printed a line on the server and called next(), and the second sent the answer.
A regular expression as a path
A path may be a regular expression instead of a string, for matching that the patterns above cannot say. Its capture groups land in req.params by number:
app.js
const express = require("express");
const app = express();
app.get(/.*fly$/, (req, res) => res.send("something that ends in fly"));
app.get(/^\/readings\/(\d+)$/, (req, res) => res.send(`reading number ${req.params[0]}`));
const server = app.listen(3000, async () => {
for (const path of ["/butterfly", "/dragonfly", "/flying", "/readings/42", "/readings/x"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/butterfly 200 something that ends in fly
/dragonfly 200 something that ends in fly
/flying 404 Cannot GET /flying
/readings/42 200 reading number 42
/readings/x 404 Cannot GET /readings/x
The first route answers any path that ends in fly. The second answers /readings/ followed by digits only, and req.params[0] holds the digits; /readings/x does not match, so Express's 404 answered.
Worked example 3
Read a reading's number from the path, refuse anything that is not a whole number above 0 with a 400, and answer 404 for a number that has no reading.
What we have: readings kept in an object by number, and a route /readings/:id whose parameter arrives as a string
What we need: three kinds of answer: 200 with the reading, 400 for a bad id, 404 for a missing one, each in JSON
The plan: convert the parameter with Number; test it with Number.isInteger and a lower bound; look the reading up; answer in that order, returning after each early answer
app.js
const express = require("express");
const app = express();
const readings = { 1: 95, 2: 40 };
app.get("/readings/:id", (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id < 1) {
return res.status(400).json({ error: `the id must be a whole number above 0, not ${req.params.id}` });
}
const value = readings[id];
if (value === undefined) return res.status(404).json({ error: `no reading ${id}` });
res.json({ id, value });
});
const server = app.listen(3000, async () => {
for (const path of ["/readings/1", "/readings/9", "/readings/one", "/readings/1.5"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/readings/1 200 {"id":1,"value":95}
/readings/9 404 {"error":"no reading 9"}
/readings/one 400 {"error":"the id must be a whole number above 0, not one"}
/readings/1.5 400 {"error":"the id must be a whole number above 0, not 1.5"}
- Number("one") is NaN and Number("1.5") is 1.5; Number.isInteger refuses both, so both get the 400.
- The 400 message quotes the raw parameter, so the client sees what it sent.
- The 404 comes only after the id passed the check: a good id that nobody has.
- Each early answer uses return, so the handler never sends twice.
/readings/1 answers 200 with the reading, /readings/9 answers 404, and /readings/one and /readings/1.5 answer 400 with a message that quotes the id.
Check: Four paths, four lines, and every bad id was caught before the lookup.
Another way: match only digits with a regular expression path, /^\/readings\/(\d+)$/, so that bad ids never reach the handler and get Express's 404 instead; the message of your own is friendlier.
A path that fails: comparing req.params.id === 1. The parameter is the string "1", never the number 1, so the comparison is always false.
When you are stuck: req.params.name is undefined, or the wrong route answered
Does the name in the route match the name you read? The route says :name and the handler reads req.params.name, letter for letter.
Is a parameter route written above a fixed one? /gauges/:name above /gauges/new catches /gauges/new with name set to new. Put fixed paths first.
Did the request have the right number of segments? A parameter takes exactly one segment; a wildcard takes the rest.
Your turn
The route is /books/:isbn and the request is /books/978-0-14. What is req.params?Tap to reveal
- A parameter takes the whole segment; hyphens inside it are plain characters.
{ isbn: "978-0-14" }, with the value as a string.
For /readings/7 with the route /readings/:id, what is typeof req.params.id?Tap to reveal
- Every parameter arrives the same way, whatever it looks like.
string. Convert it with Number when you need a number.
cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/{*rest}", (req, res) => res.json(req.params));
const server = app.listen(3000, async () => {
for (const path of ["/", "/a/b"]) console.log(path, await (await fetch("http://localhost:3000" + path)).text());
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
/ {}
/a/b {"rest":["a","b"]}
- The wildcard inside braces is optional: for / it is absent and left out of req.params.
- For /a/b it holds the two segments as an array.
It prints / {} and /a/b {"rest":["a","b"]}.
Did you know?
No patterns inside string paths
Express 5 refuses a pattern inside a string path, such as /:foo(\d+), which Express 4 accepted. The Express blog explains why: it is easy to write a regular expression that takes exponential time on some input, the attack called regular expression denial of service, or ReDoS. A last-minute change to the path rules removed that possibility.
Why it fits here: It answers this topic's question: patterns inside string paths were dropped to stop ReDoS attacks.
One callback per parameter
A parameter can have code of its own. With app.param("id", callback), the callback for id runs before any handler of any route that holds it. The Express documentation adds that it runs only once in a request, even if the parameter is matched in several routes. So one place can load the item that an id names.
Why it fits here: It adds to this topic's parameters: app.param runs one callback for a parameter, once per request, before the handlers.
In one line
A colon makes a route parameter: one segment, in req.params as a decoded string. An asterisk makes a wildcard, the rest of the path as an array, and braces make a part optional. next() goes on to the next handler, next("route") to the next route, and a regular expression path captures by number.
The query string, and the rest of the request
At a glance
After the path comes the query, the part after the question mark. Express reads it for you.
The property req.query holds the query as an object of strings. A name given twice becomes an array, and a name with no value becomes an empty string. Other parts of the request have names too: req.path is the path alone, req.url is the path with the query, and req.get reads one header, whatever its capitals. Every value arrives as text, so convert and check it before use.
Take a guess: Did Express always read a query string the same way?
After the path, a request may carry a query string: a question mark, then pairs of name=value joined by ampersands, such as /gauges?hall=engine&min=50. It is the place for choices about a list: which part of it, in which order, how many. Express parses it for you into req.query:
app.js
const express = require("express");
const app = express();
app.get("/gauges", (req, res) => {
console.log(req.query);
res.json({ query: req.query, path: req.path, url: req.url });
});
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges?hall=engine&min=50&tag=a&tag=b&name=two%20words&empty=&flag");
console.log(await r.text());
server.close();
});
Terminal: node app.js
[Object: null prototype] {
hall: 'engine',
min: '50',
tag: [ 'a', 'b' ],
name: 'two words',
empty: '',
flag: ''
}
{"query":{"hall":"engine","min":"50","tag":["a","b"],"name":"two words","empty":"","flag":""},"path":"/gauges","url":"/gauges?hall=engine&min=50&tag=a&tag=b&name=two%20words&empty=&flag"}
The server printed req.query with console.log, and the client printed the JSON. Four rules show in them. Every value is a string, so min is '50'. A name that appears twice, tag, becomes an array. A name with nothing after the equals sign, empty, and a name with no equals sign at all, flag, both give an empty string. And %20 was decoded to a space.
The object is printed with the words null prototype because it is made with no prototype at all, so a name such as constructor cannot collide with anything. It is an ordinary object to read from.
Notice req.path and req.url: the path has no query string, and the url has the whole of it. The route matched on the path alone.
Using the query
A handler reads the choices it knows and ignores the rest. Each value needs the same care as a route parameter: convert it, and refuse what does not convert. A missing choice is undefined, which is how a handler tells that the client made no choice:
app.js
const express = require("express");
const app = express();
const gauges = [{ name: "boiler", value: 95 }, { name: "pump", value: 40 }, { name: "fan", value: 20 }];
app.get("/gauges", (req, res) => {
let list = gauges;
if (req.query.min !== undefined) {
const min = Number(req.query.min);
if (!Number.isFinite(min)) return res.status(400).json({ error: `min must be a number, not ${req.query.min}` });
list = list.filter((g) => g.value >= min);
}
if (req.query.sort === "value") list = [...list].sort((a, b) => a.value - b.value);
res.json(list.map((g) => g.name));
});
const server = app.listen(3000, async () => {
for (const path of ["/gauges", "/gauges?min=30", "/gauges?min=30&sort=value", "/gauges?min=high"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/gauges 200 ["boiler","pump","fan"]
/gauges?min=30 200 ["boiler","pump"]
/gauges?min=30&sort=value 200 ["pump","boiler"]
/gauges?min=high 400 {"error":"min must be a number, not high"}
Without min, every gauge is listed. With min=30, Number turns the string into 30 and the filter keeps the gauges at or above it. With sort=value the copy is sorted; the spread makes a copy so that the shared array keeps its order. And min=high gives NaN, which Number.isFinite refuses, so the client gets a 400 that names the bad value.
The rest of the request
Besides params and query, req carries the facts of the request. req.method and req.path you have seen. req.get(name) reads one header, without regard to the case of its name, and gives undefined for a header that is not there. req.hostname is the Host header without its port, and req.protocol is http or https:
app.js
const express = require("express");
const app = express();
app.get("/info", (req, res) => {
res.json({
method: req.method, path: req.path, url: req.url, hostname: req.hostname, host: req.get("host"),
agent: req.get("User-Agent"), accept: req.get("accept"), hall: req.get("x-hall"), missing: req.get("X-Missing") ?? null, protocol: req.protocol,
});
});
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/info?x=1", { headers: { "X-Hall": "engine" } });
console.log(await r.text());
server.close();
});
Terminal: node app.js
{"method":"GET","path":"/info","url":"/info?x=1","hostname":"localhost","host":"localhost:3000","agent":"node","accept":"*/*","hall":"engine","missing":null,"protocol":"http"}
The client sent one header of its own, X-Hall, and the handler read it as x-hall. fetch added the others: a Host, an Accept of */*, which means any kind of answer, and a User-Agent, which names the client. The missing header gave undefined, written here as null so that JSON keeps it.
| Field | For /info?x=1 from localhost:3000 | What it is |
|---|---|---|
req.method | GET | the verb |
req.path | /info | the path alone |
req.url | /info?x=1 | the path and the query string |
req.query | { x: "1" } | the query string, parsed |
req.params | {} | the route's parameters |
req.get(name) | a string or undefined | one header, any case |
req.hostname | localhost | the Host header without the port |
req.protocol | http | http or https |
Worked example 4
Build /search?q=word&limit=n: the word is required, the limit is optional with a default of 10 and a ceiling of 50, and the search ignores case.
What we have: a list of gauge names, and a query string whose values arrive as strings or not at all
What we need: 200 with the matches, or 400 when q is missing or limit is not a whole number from 1 to 50
The plan: read q with a fallback and lower it; refuse an empty q; read limit with a default, convert it, test it; filter and slice; answer with the choices echoed back
app.js
const express = require("express");
const app = express();
const gauges = ["boiler", "pump", "fan", "belt", "bell"];
app.get("/search", (req, res) => {
const q = String(req.query.q ?? "").toLowerCase();
if (!q) return res.status(400).json({ error: "q is required" });
const limit = req.query.limit === undefined ? 10 : Number(req.query.limit);
if (!Number.isInteger(limit) || limit < 1 || limit > 50) {
return res.status(400).json({ error: "limit must be a whole number from 1 to 50" });
}
const found = gauges.filter((g) => g.includes(q)).slice(0, limit);
res.json({ q, limit, found });
});
const server = app.listen(3000, async () => {
for (const path of ["/search?q=b", "/search?q=B&limit=2", "/search", "/search?q=b&limit=500"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/search?q=b 200 {"q":"b","limit":10,"found":["boiler","belt","bell"]}
/search?q=B&limit=2 200 {"q":"b","limit":2,"found":["boiler","belt"]}
/search 400 {"error":"q is required"}
/search?q=b&limit=500 400 {"error":"limit must be a whole number from 1 to 50"}
req.query.q ?? ""gives an empty string when q is missing, and the empty string fails the check.- toLowerCase makes B find boiler: the search ignores case on both sides.
- limit is 10 when absent; 500 passes Number but fails the ceiling, so it gets the 400.
- The answer echoes q and limit as the handler understood them, which helps a client see what happened.
q=b finds boiler, belt and bell; with limit=2 only the first two; no q answers 400 q is required; limit=500 answers 400 with the rule.
Check: Four requests, four lines; the two bad ones were refused with a reason, and the good ones got exactly what they asked for.
Another way: keep the checks in a small function, checkLimit(value), that returns either a number or an error message, so that every handler with a limit can share it.
A path that fails: writing if (req.query.limit > 50). The value is a string; "500" > 50 happens to be true after conversion, but "abc" > 50 is false and would pass. Convert first, then check.
When you are stuck: The filter ignores the number, or a value is an array
Every value of req.query is a string. Compare numbers only after Number(), and check the result with Number.isFinite or Number.isInteger.
A name sent twice gives an array. If a client may repeat it, handle both: [].concat(req.query.tag) makes a one-element array of a single value.
The query string is not in req.path, so a route path can never match it. Read choices from req.query, never from the path.
Your turn
What is req.query for the request /list?a=1&a=2&b=?Tap to reveal
- A repeated name becomes an array; an empty value is an empty string.
{ a: ["1", "2"], b: "" }, every value a string.
For /gauges?min=50, which of req.path and req.url holds the question mark and what follows it?Tap to reveal
- One is the path alone, one is the whole of it.
req.url holds /gauges?min=50; req.path is /gauges.
cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/n", (req, res) => res.send(typeof req.query.n + " " + (req.query.n + 1)));
const server = app.listen(3000, async () => {
console.log(await (await fetch("http://localhost:3000/n?n=5")).text());
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
string 51
- req.query.n is the string "5".
- A string plus a number joins them as text: "5" + 1 is "51".
It prints string 51: the value is a string, so + joined instead of adding.
Did you know?
Express 5 reads queries the plain way
Express 5 changed how it reads a query. Its migration guide says that the default query parser changed from extended to simple. The simple one is Node's own querystring. The extended one is the package qs, which builds nested objects from names in square brackets, so foo[bar]=baz became an object inside an object. A setting brings the old way back.
Why it fits here: It answers this topic's question: Express 4 read queries with qs, nested objects and all, and Express 5 with Node's querystring.
Sources: Express: Migrating to Express 5; Express 5.x API: Application (settings); qs on GitHub
Faster, or standard
Node has two readers of query strings, and its manual compares them. The querystring module is more performant than URLSearchParams, it says, but it is not a standardized API. So the manual advises URLSearchParams when speed is not critical, or when the code must also run in a browser, where URLSearchParams exists as well.
Why it fits here: It adds to this topic's query: Node's querystring is faster, while URLSearchParams is the standard one that browsers share.
Source: Node.js manual: Query string
In one line
req.query holds the query string as an object of strings, with an array for a repeated name and an empty string for a bare one. The path alone is req.path, the whole is req.url, and req.get reads one header in any case. Convert and check every value before use.
Sending the answer
At a glance
A handler ends by answering, and Express has a method for every kind of answer.
The method res.send labels what it is given: a string as HTML, an object or a number as JSON, and bytes as bytes. The method res.status sets the status code and can be chained before the answer. The methods res.json, sendStatus, end, set, type and redirect cover the rest. Each request gets exactly one answer, so a handler returns right after it, before it can send a second.
Take a guess: Can following a redirect change a POST into a GET?
Every request needs one answer, and only one. The handler's second argument, res, has helpers that set the status, set the headers, write the body and end the response.
The helper used most is res.send. It looks at what it was given and labels it to match. Here it is given five kinds of thing:
app.js
const express = require("express");
const app = express();
app.get("/text", (req, res) => res.send("<b>hi</b>"));
app.get("/object", (req, res) => res.send({ a: 1 }));
app.get("/number", (req, res) => res.send(42));
app.get("/bytes", (req, res) => res.send(Buffer.from("hi")));
app.get("/nothing", (req, res) => res.send(null));
const server = app.listen(3000, async () => {
for (const path of ["/text", "/object", "/number", "/bytes", "/nothing"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.headers.get("content-type"), r.headers.get("content-length"), JSON.stringify(await r.text()));
}
server.close();
});
Terminal: node app.js
/text text/html; charset=utf-8 9 "<b>hi</b>"
/object application/json; charset=utf-8 7 "{\"a\":1}"
/number application/json; charset=utf-8 2 "42"
/bytes application/octet-stream 2 "hi"
/nothing null 0 ""
| Given to res.send | Content-Type it sets | The body |
|---|---|---|
| a string | text/html; charset=utf-8 | the string itself |
| an object or an array | application/json; charset=utf-8 | its JSON text |
| a number | application/json; charset=utf-8 | the number as JSON text |
| a Buffer of bytes | application/octet-stream | the bytes as they are |
null | none | an empty body |
A string counts as HTML unless you set another type, because a browser was Express's first client. An object goes as JSON, as res.json would send it.
Look again at the number. res.send(42) sends the text 42 as JSON with the status 200. Older Express read a lone number as a status; Express 5 does not, so a status is always set with res.status.
The status, and answers without a body
res.status(code) sets the status and gives back res itself, so the next call can follow on the same line. res.json(data) always sends JSON. res.sendStatus(code) sets the status and sends its name, such as Not Found, as plain text. res.end() ends the response with no body at all:
app.js
const express = require("express");
const app = express();
app.post("/gauges", (req, res) => res.status(201).json({ name: "fan", value: 20 }));
app.get("/gauges/fan", (req, res) => res.sendStatus(404));
app.delete("/gauges/fan", (req, res) => res.status(204).end());
app.get("/kettle", (req, res) => res.status(418).send("I am a teapot"));
const server = app.listen(3000, async () => {
const asks = [["POST", "/gauges"], ["GET", "/gauges/fan"], ["DELETE", "/gauges/fan"], ["GET", "/kettle"]];
for (const [method, path] of asks) {
const r = await fetch("http://localhost:3000" + path, { method });
console.log(method, path, r.status, r.statusText, JSON.stringify(await r.text()));
}
server.close();
});
Terminal: node app.js
POST /gauges 201 Created "{\"name\":\"fan\",\"value\":20}"
GET /gauges/fan 404 Not Found "Not Found"
DELETE /gauges/fan 204 No Content ""
GET /kettle 418 I'm a Teapot "I am a teapot"
The new gauge got 201 Created with its JSON. The missing one got 404 and the words Not Found from sendStatus. The delete got 204 No Content and an empty body, as a 204 must have. And any code from 100 to 999 is allowed: 418 is a real one, kept from an old joke, and Node knows its name.
| Call | Status | Body |
|---|---|---|
res.send(data) | 200, or the one set before | data, labelled by its kind |
res.json(data) | 200, or the one set before | JSON, always |
res.status(201).json(data) | 201 | JSON |
res.sendStatus(404) | 404 | Not Found, as plain text |
res.status(204).end() | 204 | none |
Headers of your own
res.set(name, value) sets a header, and res.get(name) reads back one that is set. res.type(kind) sets the Content-Type from a short name such as txt, json or html, and adds the charset:
app.js
const express = require("express");
const app = express();
app.get("/plain", (req, res) => {
res.set("X-Yard", "east").type("txt");
console.log("set so far:", res.get("Content-Type"), res.get("X-Yard"));
res.send("plain words");
});
app.get("/list", (req, res) => res.type("json").send("[1,2]"));
const server = app.listen(3000, async () => {
for (const path of ["/plain", "/list"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.headers.get("content-type"), r.headers.get("x-yard"), await r.text());
}
server.close();
});
Terminal: node app.js
set so far: text/plain; charset=utf-8 east
/plain text/plain; charset=utf-8 east plain words
/list application/json; charset=utf-8 null [1,2]
The first route set two headers, read them back on the server, then sent the body. The second labelled a string as JSON with type, so send kept that label instead of calling it HTML. A header that was never set reads as null on the client.
Redirects
A redirect tells the client that the thing it asked for lives at another address. res.redirect(path) answers 302 Found with a Location header; res.redirect(301, path) answers 301 Moved Permanently, for an address that moved for good:
app.js
const express = require("express");
const app = express();
app.get("/boiler", (req, res) => res.redirect("/gauges/boiler"));
app.get("/old-gauges", (req, res) => res.redirect(301, "/gauges"));
const server = app.listen(3000, async () => {
for (const path of ["/boiler", "/old-gauges"]) {
const r = await fetch("http://localhost:3000" + path, { redirect: "manual" });
console.log(path, r.status, r.headers.get("location"), await r.text());
}
server.close();
});
Terminal: node app.js
/boiler 302 /gauges/boiler Found. Redirecting to /gauges/boiler
/old-gauges 301 /gauges Moved Permanently. Redirecting to /gauges
Each redirect carries the new address in Location and a short text body for anyone who reads it. fetch follows a redirect by itself unless it is told not to, and the client would then see only the final answer. These blocks pass redirect: "manual" so that the redirect itself shows.
One answer, and only one
Once the head of a response has gone, nothing can change it. A handler that tries to answer twice gets an error on the second try. This handler forgot a return, so the missing gauge fell through to the second answer:
app.js
const express = require("express");
const app = express();
app.get("/gauges/:name", (req, res) => {
if (req.params.name !== "boiler") {
res.status(404).json({ error: "no such gauge" });
}
try {
res.json({ name: "boiler", value: 95 });
} catch (e) {
console.log("the second answer failed:", e.code);
}
});
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges/fan");
console.log(r.status, await r.text());
server.close();
});
Terminal: node app.js
the second answer failed: ERR_HTTP_HEADERS_SENT
404 {"error":"no such gauge"}
The client got the first answer, the 404, and nothing else. The second call of res.json failed with the code ERR_HTTP_HEADERS_SENT: the headers were sent already. The try and catch are there only to show the error; the fix is to write return res.status(404).json(...), so the handler stops at its answer.
When a handler must check, res.headersSent is true once the head has gone.
Worked example 5
Write a small gauges API that answers every case with the right status: a list, one gauge or 404, a delete that answers 204 or 404, and an old address that moved for good.
What we have: two gauges in an object, and the helpers status, json, sendStatus, end and redirect
What we need: six answers in a row from one client: 200, 204, 404, 404, 301 and 200
The plan: one route per verb and path; check the name with Object.hasOwn and return early with the 404; delete answers 204 with no body; the old address redirects with 301
app.js
const express = require("express");
const app = express();
const gauges = { boiler: 95, pump: 40 };
app.get("/gauges", (req, res) => res.json(gauges));
app.get("/gauges/:name", (req, res) => {
if (!Object.hasOwn(gauges, req.params.name)) return res.status(404).json({ error: `no gauge called ${req.params.name}` });
res.json({ name: req.params.name, value: gauges[req.params.name] });
});
app.delete("/gauges/:name", (req, res) => {
if (!Object.hasOwn(gauges, req.params.name)) return res.sendStatus(404);
delete gauges[req.params.name];
res.status(204).end();
});
app.get("/meters", (req, res) => res.redirect(301, "/gauges"));
const server = app.listen(3000, async () => {
const asks = [["GET", "/gauges/pump"], ["DELETE", "/gauges/pump"], ["DELETE", "/gauges/pump"], ["GET", "/gauges/pump"], ["GET", "/meters"], ["GET", "/gauges"]];
for (const [method, path] of asks) {
const r = await fetch("http://localhost:3000" + path, { method, redirect: "manual" });
console.log(method, path, r.status, r.headers.get("location") ?? "-", JSON.stringify(await r.text()));
}
server.close();
});
Terminal: node app.js
GET /gauges/pump 200 - "{\"name\":\"pump\",\"value\":40}"
DELETE /gauges/pump 204 - ""
DELETE /gauges/pump 404 - "Not Found"
GET /gauges/pump 404 - "{\"error\":\"no gauge called pump\"}"
GET /meters 301 /gauges "Moved Permanently. Redirecting to /gauges"
GET /gauges 200 - "{\"boiler\":95}"
- The first GET finds the pump and answers 200 with its JSON.
- The first DELETE removes it and answers 204 with an empty body; the second finds nothing and answers 404 with sendStatus's Not Found.
- The GET after the delete answers the route's own 404, in JSON, because the pump is gone.
- /meters answers 301 with Location /gauges, and the last GET shows the one gauge left.
The six lines read 200, 204, 404, 404, 301 and 200, each with the body its status calls for.
Check: Every early answer has a return, so no request got two answers, and the list at the end shows the delete took effect.
Another way: answer the missing gauge on DELETE with a JSON error too, as GET does, so that a client always gets JSON from this API.
A path that fails: writing res.send(404) for a missing gauge. In Express 5 that sends the number 404 as JSON with the status 200, so the client thinks it worked.
When you are stuck: The wrong status, an empty body, or ERR_HTTP_HEADERS_SENT
Did the handler set the status before sending? res.status(404).json(...) sets it; res.json(...) alone answers 200.
Did an early answer have a return in front of it? Without it, the handler carries on and answers twice.
Was the body sent with res.end? end sends nothing of its own; use res.send or res.json for a body.
Did fetch follow a redirect? Pass redirect: "manual" to see the 3xx answer itself.
Your turn
Which call answers 201 with the JSON {"ok":true}?Tap to reveal
- The status first, then the JSON, on one line.
res.status(201).json({ ok: true }).
What do res.sendStatus(404) and res.status(204).end() send as a body?Tap to reveal
- One sends the status's name; one sends nothing.
sendStatus sends Not Found as plain text; end sends no body.
cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send([1, 2]));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/");
console.log(r.headers.get("content-type"), await r.text());
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
application/json; charset=utf-8 [1,2]
- An array is an object, so res.send sends it as JSON.
- The label is application/json with the charset added.
It prints application/json; charset=utf-8 [1,2].
Did you know?
Redirects that keep the method
A redirect can change the method. RFC 9110 notes that, for historical reasons, a client may change a POST into a GET when it follows a 301 or a 302. To keep the method, a server answers 307 Temporary Redirect or 308 Permanent Redirect instead. The code 308 became a standard with RFC 7538 of April 2015, which replaced RFC 7238.
Why it fits here: It answers this topic's question: after 301 or 302 a POST may become a GET, while 307 and 308 keep it a POST.
Sources: RFC 9110: HTTP Semantics; RFC 7538: The Hypertext Transfer Protocol Status Code 308 (Permanent Redirect)
Escaped JSON, on request
Express can write its JSON more cautiously. Its setting json escape, off unless set, makes res.json and res.send write the characters <, > and & as Unicode escape sequences. The documentation says the purpose is to help against certain persistent XSS attacks, when clients sniff a response for HTML; the escaped text still reads as the same JSON.
Why it fits here: It adds to this topic's res.json: one setting escapes <, > and &, against attacks that treat JSON as HTML.
In one line
res.send labels what it is given: a string as HTML, an object or a number as JSON, bytes as bytes. res.status sets the status and chains, and res.json, sendStatus, end, set, type and redirect cover the rest. Every answer is the only one, so return after it.
Routers: routes in groups
At a glance
A big API has many routes, and one file cannot hold them all well. Express lets you group them, a group to a file.
The call express.Router() makes a router, a group of routes written as if from its own root. The call app.use(path, router) mounts it at a path. Inside, req.baseUrl is the mount path, req.url the rest, and req.originalUrl the whole. The option mergeParams lets a router read the parameters of its mount path, and app.route chains several verbs on one path.
Take a guess: Is Express's router a part of Express, or a package of its own?
As an API grows, its routes pile up in one file: ten for the gauges, ten for the halls, ten for the couriers. A router holds the routes of one group. It has get, post, all and the rest, like the app, but no listen of its own.
You make one with express.Router(), fill it with routes, then mount it on the app at one path with app.use(path, router). Inside the router, every path is written from that mount point:
app.js
const express = require("express");
const app = express();
const gauges = express.Router();
gauges.get("/", (req, res) => res.json({ list: ["boiler", "pump"], baseUrl: req.baseUrl, url: req.url }));
gauges.get("/:name", (req, res) => res.json({ name: req.params.name, baseUrl: req.baseUrl, url: req.url, originalUrl: req.originalUrl }));
app.use("/gauges", gauges);
const server = app.listen(3000, async () => {
for (const path of ["/gauges", "/gauges/boiler", "/gauges/boiler/x"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/gauges 200 {"list":["boiler","pump"],"baseUrl":"/gauges","url":"/"}
/gauges/boiler 200 {"name":"boiler","baseUrl":"/gauges","url":"/boiler","originalUrl":"/gauges/boiler"}
/gauges/boiler/x 404 Cannot GET /gauges/boiler/x
The router's paths are / and /:name, and mounted at /gauges they answer /gauges and /gauges/boiler. Inside it, req.baseUrl is the mount path, req.url is what is left after it, and req.originalUrl is the whole path as it arrived. /gauges/boiler/x matched no route of the router, so Express's 404 answered.
| Field | For /gauges/boiler, router at /gauges | What it is |
|---|---|---|
req.baseUrl | /gauges | where the router is mounted |
req.url | /boiler | the rest, which the router's routes match |
req.originalUrl | /gauges/boiler | the whole path, as it arrived |
req.path | /boiler | req.url without a query string |
A router in a file of its own
A router's real gift is a file of its own. The file builds the router and exports it; the app requires it and mounts it. The page shows gauges.js first, then the app that uses it:
gauges.js
const express = require("express");
const router = express.Router();
const gauges = { boiler: 95, pump: 40 };
router.get("/", (req, res) => res.json(gauges));
router.get("/:name", (req, res) => {
if (!Object.hasOwn(gauges, req.params.name)) return res.status(404).json({ error: "no such gauge" });
res.json({ name: req.params.name, value: gauges[req.params.name] });
});
module.exports = router;
app.js
const express = require("express");
const gauges = require("./gauges");
const app = express();
app.use("/gauges", gauges);
app.get("/", (req, res) => res.send("the yard's front door"));
const server = app.listen(3000, async () => {
for (const path of ["/", "/gauges", "/gauges/pump", "/gauges/fan"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, await r.text());
}
server.close();
});
Terminal: node app.js
/ 200 the yard's front door
/gauges 200 {"boiler":95,"pump":40}
/gauges/pump 200 {"name":"pump","value":40}
/gauges/fan 404 {"error":"no such gauge"}
module.exports = router is the whole interface of gauges.js. The app knows nothing of the gauges' routes: it mounts the router at /gauges and moves on. A big API has one such file per resource, often in a folder called routes, and the app file shrinks to a list of mounts.
The mount path's parameters
A mount path may hold parameters too, such as /halls/:hall/gauges. By default a router does not see them: its req.params holds only its own. The option mergeParams: true lets the router see its mount path's parameters as well:
app.js
const express = require("express");
const app = express();
const withHall = express.Router({ mergeParams: true });
withHall.get("/:name", (req, res) => res.json(req.params));
const withoutHall = express.Router();
withoutHall.get("/:name", (req, res) => res.json(req.params));
app.use("/halls/:hall/gauges", withHall);
app.use("/plain/:hall/gauges", withoutHall);
const server = app.listen(3000, async () => {
for (const path of ["/halls/engine/gauges/boiler", "/plain/engine/gauges/boiler"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, await r.text());
}
server.close();
});
Terminal: node app.js
/halls/engine/gauges/boiler {"hall":"engine","name":"boiler"}
/plain/engine/gauges/boiler {"name":"boiler"}
The two routers are the same except for the option. With mergeParams, req.params held the hall from the mount path and the name from the router's own route. Without it, the hall was not there.
app.route: one path, several verbs
app.route(path) names a path once and chains a handler for each verb onto it. It saves writing the same path three times, and a typo in one of them:
app.js
const express = require("express");
const app = express();
app.route("/book")
.get((req, res) => res.send("read the book"))
.post((req, res) => res.status(201).send("a page added"))
.put((req, res) => res.send("the book replaced"));
const server = app.listen(3000, async () => {
for (const method of ["GET", "POST", "PUT", "DELETE"]) {
const r = await fetch("http://localhost:3000/book", { method });
console.log(method, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
GET 200 read the book
POST 201 a page added
PUT 200 the book replaced
DELETE 404 Cannot DELETE /book
GET, POST and PUT each reached their handler. DELETE had none, so Express answered 404. A router has route too, so the same chain works inside a router.
Worked example 6
Mount the yard's API under /api in one router, and give it a JSON 404 of its own, while the rest of the site keeps Express's HTML page.
What we have: a router with two gauge routes, a front door on the app, and the wildcard route of an earlier section
What we need: JSON answers for every address under /api, found or not, and the HTML 404 for anything else
The plan: fill the router with its routes; add api.all("/{*rest}") as its last route, answering 404 in JSON; mount the router at /api; keep the front door on the app
app.js
const express = require("express");
const app = express();
const api = express.Router();
const gauges = { boiler: 95, pump: 40 };
api.get("/gauges", (req, res) => res.json(gauges));
api.get("/gauges/:name", (req, res) => {
if (!Object.hasOwn(gauges, req.params.name)) return res.status(404).json({ error: "no such gauge" });
res.json({ name: req.params.name, value: gauges[req.params.name] });
});
api.all("/{*rest}", (req, res) => res.status(404).json({ error: `no route for ${req.method} ${req.originalUrl}` }));
app.use("/api", api);
app.get("/", (req, res) => res.send("front door"));
const server = app.listen(3000, async () => {
for (const path of ["/api/gauges", "/api/gauges/pump", "/api/nothing", "/nothing"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/api/gauges 200 {"boiler":95,"pump":40}
/api/gauges/pump 200 {"name":"pump","value":40}
/api/nothing 404 {"error":"no route for GET /api/nothing"}
/nothing 404 Cannot GET /nothing
- The gauge routes answer as before, now under /api.
- /api/nothing matched no gauge route, so it reached the router's last route, which answers every verb and every path under /api.
- req.originalUrl gives the whole path in the message, /api/nothing, not the router's /nothing.
- /nothing is outside the router, so Express's own HTML 404 answered it.
The API answers 200 for the gauges and 404 in JSON for /api/nothing; the site answers Cannot GET /nothing outside /api.
Check: Four paths, four lines, and every answer under /api was JSON.
Another way: give the router a version in its mount path, app.use("/api/v1", api), so that a second version can be mounted beside it later.
A path that fails: writing the routes inside the router as /api/gauges. The mount adds /api already, so the route would answer /api/api/gauges.
When you are stuck: A router's route never answers
Is the router mounted? app.use("/gauges", gauges) is what connects it; a router that is only created answers nothing.
Are its paths written from the mount point? Inside a router at /gauges, the list is "/", not "/gauges".
Does a route read a parameter of the mount path? Make the router with express.Router({ mergeParams: true }).
Your turn
A router is mounted at /halls, and a request comes for /halls/engine. What are req.baseUrl and req.url?Tap to reveal
- One is the mount path; the other is what is left.
req.baseUrl is /halls and req.url is /engine.
Which option lets a router read :hall from the mount path /halls/:hall/gauges?Tap to reveal
- It merges the mount path's parameters into the router's.
express.Router({ mergeParams: true }).
cat > app.js <<'END'
const express = require("express");
const app = express();
const r = express.Router();
r.get("/list", (req, res) => res.send(req.originalUrl));
app.use("/gauges", r);
const server = app.listen(3000, async () => {
console.log(await (await fetch("http://localhost:3000/gauges/list")).text());
server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
/gauges/list
- The router's route /list answers /gauges/list, because the router is mounted at /gauges.
- req.originalUrl is the whole path as it arrived.
It prints /gauges/list.
Did you know?
A router of its own
Express does not do its routing alone. Its package.json, at version 5.3.0, lists router among its dependencies: a separate package, which its project describes as a simple middleware-style router. Its README says that it was extracted from the Express project, and its example runs it on a plain Node server, with no Express at all.
Why it fits here: It answers this topic's question: Express's routing comes from router, a package of its own that Express depends on.
app.router came back
One name left Express and returned. The Express 5 migration guide says that the app.router object, removed in Express 4, has made a comeback in Express 5. Now it is a reference to the app's own base router, created on first access, while in Express 3 an app had to load it explicitly.
Why it fits here: It adds to this topic's routers: every app has a built-in router, reachable again as app.router since Express 5.
Sources: Express: Migrating to Express 5; Express 5.x API: Application (app.router)
In one line
express.Router() holds a group of routes, written from its mount point; app.use(path, router) mounts it; req.baseUrl is the mount, req.url the rest and req.originalUrl the whole; mergeParams lets it read the mount's parameters; app.route chains verbs on one path.
Where it is used
Express, or a router much like it, sits under a great many of the APIs you will meet. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| routes, a verb and a path | every REST API built on Node | a shop's API with GET /products and POST /orders |
| route parameters | every address that names one thing | GET /orders/:id for one order |
| the query string | lists that filter, sort and page | GET /products?category=books&page=2 |
| status and JSON answers | every JSON API | 201 Created with the new order in JSON |
| redirects | moved addresses and sign-in flows | an old /shop sending 301 to /store |
| routers in files | every API of more than a few routes | routes/orders.js and routes/users.js, mounted by one app.js |
Other routers for Node, such as Fastify, Koa and Hono, write the same ideas in their own way: a verb, a path with parameters, a handler, an answer. What you learned here carries over to them.
In the Couriers' Yard, the routes are the benches beside the belt, and Express is the machine that reads every label and sends each parcel to its bench.
Mistakes and debugging
These are the mistakes that routing beginners make most, each with the way to see it and the fix.
1. A parameter compared with a number
A route parameter is always a string, so comparing it with a number using === is always false:
app.js
const express = require("express");
const app = express();
app.get("/readings/:id", (req, res) => {
res.json({ strict: req.params.id === 1, converted: Number(req.params.id) === 1 });
});
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/readings/1");
console.log(await r.text());
server.close();
});
Terminal: node app.js
{"strict":false,"converted":true}
Convert first with Number, then compare, and check the result with Number.isInteger when the id must be whole.
2. A parameter route above a fixed one
Routes are tried in order, and :name matches any one segment, the word new included:
app.js
const express = require("express");
const app = express();
app.get("/gauges/:name", (req, res) => res.send(`the gauge called ${req.params.name}`));
app.get("/gauges/new", (req, res) => res.send("the form for a new gauge"));
const server = app.listen(3000, async () => {
const r = await fetch("http://localhost:3000/gauges/new");
console.log(await r.text());
server.close();
});
Terminal: node app.js
the gauge called new
The fixed route never answered. Write fixed paths such as /gauges/new above the parameter route /gauges/:name, and catch-alls last of all.
3. A router's paths written in full
Inside a router, paths start from the mount point. Writing the mount path again doubles it:
app.js
const express = require("express");
const app = express();
const gauges = express.Router();
gauges.get("/gauges", (req, res) => res.send("the list"));
app.use("/gauges", gauges);
const server = app.listen(3000, async () => {
for (const path of ["/gauges", "/gauges/gauges"]) {
const r = await fetch("http://localhost:3000" + path);
console.log(path, r.status);
}
server.close();
});
Terminal: node app.js
/gauges 404
/gauges/gauges 200
The route meant for /gauges answered /gauges/gauges instead. Inside a router mounted at /gauges, the list's path is /.
4. Two answers to one request
An answer inside an if, without return, lets the handler run on to its next answer, which fails with ERR_HTTP_HEADERS_SENT, as the section on answers showed. Put return in front of every early answer.
5. A redirect that fetch followed
fetch follows redirects by itself, so a client that expects a 301 sees the final page's 200 instead. Pass redirect: "manual" when the redirect itself is what you want to see.
The debugging corner: print what Express saw
When a route does not answer, put this route first: app.all("/{*any}", (req, res, next) => { console.log(req.method, req.originalUrl); next(); }). It prints every request's verb and whole path, and next() passes the request on to the routes below.
Then compare what was printed with your route's verb and path, letter by letter. The 404 page says the same thing: Cannot GET /path names exactly the verb and the path that found no route.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
app.js
const express = require("express");
const app = express();
const gauges = express.Router();
const values = { boiler: 95, pump: 40 };
gauges.get("/", (req, res) => {
const min = Number(req.query.min ?? 0);
res.json(Object.keys(values).filter((name) => values[name] >= min));
});
gauges.get("/:name", (req, res) => {
if (!Object.hasOwn(values, req.params.name)) return res.status(404).json({ error: "no such gauge" });
res.json({ name: req.params.name, value: values[req.params.name] });
});
app.use("/gauges", gauges);
app.get("/meters", (req, res) => res.redirect(301, "/gauges"));
const server = app.listen(3000, async () => {
for (const path of ["/gauges?min=50", "/gauges/pump", "/gauges/fan", "/meters", "/nowhere"]) {
const r = await fetch("http://localhost:3000" + path, { redirect: "manual" });
console.log(path, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
}
server.close();
});
Terminal: node app.js
/gauges?min=50 200 ["boiler"]
/gauges/pump 200 {"name":"pump","value":40}
/gauges/fan 404 {"error":"no such gauge"}
/meters 301 Moved Permanently. Redirecting to /gauges
/nowhere 404 Cannot GET /nowhere
| When you see | It means | Do |
|---|---|---|
Cannot GET /path | no route has that verb and path | check the verb, the spelling, the leading slash and the mount |
| the wrong route answers | an earlier route matched first | fixed paths before parameter routes; catch-alls last |
req.params.id === 1 is false | parameters are strings | Number(), then Number.isInteger |
| a query value that is an array | the name was sent twice | [].concat(value), or take the first |
ERR_HTTP_HEADERS_SENT | a second answer to one request | return after every answer |
| a 200 where a redirect was expected | fetch followed the redirect | redirect: "manual" |
| a mount's parameter is undefined | the router does not see it | express.Router({ mergeParams: true }) |
TypeError: Unexpected ( at index | a reserved character in a path | escape it, or use a parameter or a pattern |
The story: Every parcel to its bench
You set the benches. One bench answers for the list of gauges, one for a single gauge named in the address, one takes new readings. A bench can read a name out of the address, and a note after the question mark in it. Whole rows of benches move onto a cart of their own, wheeled to the belt at one address.
A parcel for a bench that does not exist comes back at once with the yard's own stamp: Cannot GET, and the address. Nobody waits.
The queue is gone by lunch. "Tomorrow," says the Yardmaster, "the checkpoints along the belt, where a parcel is weighed and opened before any bench sees it."
Reagents gathered: Express, route, path, route parameter, query string, router.
Sources
- The Express documentation (CC BY-SA 3.0 US (the site's footer, read 2026-11-15); facts and ideas only)
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)