The server from the last lesson has a single route, and it's already full of ifs: check the method, check the path, drop the query string, then JSON.stringify, writeHead and end. With twenty routes, server.js would be nothing but ifs.
Express takes care of that boring part. Express is a small framework on top of the http module. You just write "when GET /notes comes in, answer like this", and Express matches every request to its answer. Each "when ... comes in, answer like this" is called a route, and the function that answers is called the handler.
Installing Express
Express isn't built in, so install it from npm in the project folder first:
npm install express
npm downloads it into the node_modules folder (where packages from npm are kept), then records it in package.json as "express": "^5.2.1". The number may be newer, for example 5.3.0. The version installed today is Express 5. Many tutorials still use Express 4. The differences are covered below.
The notes server, Express version
Here is the previous lesson's server.js, rewritten as app.js with Express, plus two new routes:
const express = require("express");
const app = express();
app.use(express.json());
const notes = [
{ id: 1, title: "Groceries", content: "buy 5 kg of rice" },
{ id: 2, title: "Study", content: "Node.js chapter" },
];
app.get("/notes", (req, res) => {
res.json(notes);
});
app.get("/notes/:id", (req, res) => {
const item = notes.find((n) => n.id === Number(req.params.id));
if (!item) {
return res.status(404).json({ error: "Note not found" });
}
res.json(item);
});
app.post("/notes", (req, res) => {
const { title, content } = req.body;
const newNote = { id: notes.length + 1, title, content };
notes.push(newNote);
res.status(201).json(newNote);
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
require("express")returns a function, andexpress()calls it to make the application,app.app.get(path, handler)registers a route: aGETrequest to that path is answered by that handler. Registering doesn't run anything yet. The handler is called only when its request arrives.app.postis the same, forPOST.res.json(data)does three things at once:JSON.stringify, sets the headerContent-Type: application/json; charset=utf-8, then sends and closes the answer.res.status(201).json(newNote)sets the status first, then sendsnewNoteas JSON.201 Createdmeans something new was made.app.listen(3000)starts the server on port 3000, just likeserver.listen.
Matching a request to a route
| Request | Matching route | Answer |
|---|---|---|
GET /notes |
GET /notes |
200, two notes |
GET /notes/2 |
GET /notes/:id, req.params.id = "2" |
200, {"id":2,"title":"Study","content":"Node.js chapter"} |
GET /notes/9 |
GET /notes/:id, req.params.id = "9" |
404, {"error":"Note not found"} |
GET /notes?sort=title |
GET /notes, req.query.sort = "title" |
200, two notes |
DELETE /notes/1 |
none | 404 from Express: Cannot DELETE /notes/1 |
:idis a route parameter. It captures one part of the path, whatever it holds, intoreq.params.id. It's always text, so convert it withNumber(...)before you compare it with the numericid.- The query string isn't part of the match. It goes into
req.query. - When no route matches, Express answers by itself with a 404 and a small HTML page saying
Cannot DELETE /notes/1. Your handlers aren't called at all. - Express ignores letter case, and it ignores a slash at the end of the path:
/Notes/2/still matches/notes/:id.
Reading the body: express.json()
To add a new note, the client (the program that sends the request) sends a JSON body. In this curl command, -X POST picks the method, -H adds a header, and -d holds the body:
curl -i -X POST http://localhost:3000/notes -H "Content-Type: application/json" -d '{"title":"Workout","content":"run 5 km"}'
app.use(express.json()) installs a middleware: a function that runs for every request, before the route's handler. This middleware reads the JSON body and puts the result in req.body. So the POST /notes handler gets { title: "Workout", content: "run 5 km" }, then answers 201 with {"id":3,"title":"Workout","content":"run 5 km"}.
Without app.use(express.json()), nothing reads the body, and req.body holds undefined. The line const { title, content } = req.body; then throws TypeError: Cannot destructure property 'title' of 'req.body' as it is undefined., and Express answers 500 Internal Server Error. Unlike a server made with the http module, Express catches errors from handlers, so the server stays alive.
In the exercise: a route with no real request
In the exercise, all three output lines are printed with console.log, not by a real request. The starter code already makes app and prints the first line, Express app created!. Register app.get("/hello", ...) that answers res.json({ message: "Hello, World!" }), then print the next two lines yourself. The checker also sends one pretend request, GET /hello, to your app:
Express app created!
Route registered: GET /hello
Response: {"message":"Hello, World!"}
📌 Express 4 or 5?
npm install express now installs Express 5. This is what differs from Express 4 tutorials, for what this lesson covers:
- An error thrown in an
asynchandler is caught by Express and answered with a 500. Express 4 doesn't catch that error, and on current Node versions the whole server stops with it. - When the body isn't JSON,
express.json()in Express 5 leavesreq.bodyasundefined. Express 4 set it to{}. req.querycan only be read, not replaced. And?a[b]=1is no longer turned into a nested object (an object inside an object).- A path with a star (meaning: anything) must be named:
/*in Express 4 becomes/*splatin Express 5.
⚠️ Why a 404, a 500, or a vanished note?
- Forgetting
app.use(express.json()).req.bodybecomesundefined, and reading it ends in a 500. - Comparing
req.params.idstraight with a number.2 === "2"isfalse, soGET /notes/2is always a 404. UseNumber(req.params.id). - Forgetting
returnbeforeres.status(404).json(...). The code goes on tores.json(item), even though the answer was already sent. One request, one answer. - Data lost when the server restarts. The
notesarray only lives in memory. Notes added withPOSTare gone as soon as the server stops, until we use a database later.
TL;DR: Express is a small framework on top of the http module. Install it with npm install express (Express 5 today), load it with const express = require("express"), then make the app with const app = express(). Register routes (a method and a path to answer) with app.get and app.post. The handler (the function that answers in each route) answers with res.json(data) or res.status(201).json(data). Start the server with app.listen(3000). The part of the path at :id goes into req.params.id (as text), and the query string (the part after ?) goes into req.query. Install app.use(express.json()) so a JSON body is read into req.body. Without that line, req.body is undefined. A request that matches no route is answered by Express itself with a 404.
⚡ One route, one handler
Write:
const express = require("express");
const app = express();
app.get("/notes", (req, res) => {
res.json(notes);
});
app.listen(3000);
Meaning: Express is a small framework on top of the http module, and express() makes its application, app. app.get(path, handler) registers a route: a GET /notes request is answered by the handler, the function next to it. notes is the array of notes. res.json turns the data into JSON, sets its header, then sends and closes the answer. app.listen(3000) starts the server on port 3000.
⚡ :id captures part of the path
Write:
app.get("/notes/:id", (req, res) => {
const item = notes.find((n) => n.id === Number(req.params.id));
if (!item) {
return res.status(404).json({ error: "Note not found" });
}
res.json(item);
});
Guess first: for GET /notes/2, req.params.id holds the text "2". Without Number(...), what is the answer?
Always 404. n.id is a number, and 2 === "2" is false, so find finds nothing.
Meaning: :id captures one part of the path into req.params.id, and it is always text. So convert it first with Number(...). If the note doesn't exist, return res.status(404).json(...) answers 404 and stops the handler. The query string (the part after ?) isn't part of the route match. It goes into req.query.
⚡ A JSON body needs express.json()
Write:
app.use(express.json());
Meaning: This line installs a middleware, a function that runs for every request before the route's handler. This middleware reads the JSON body and puts the result in req.body. Without this line, req.body holds undefined, and reading it ends in a 500 (an error on the server).