Express.js Basics — Node.js

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 =…

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");
});

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

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:

⚠️ Why a 404, a 500, or a vanished note?

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).

What you will learn