Your First Express App: Routes and JSON
Express turns each endpoint into one line that names its method and path, answers with res.json, and reads a JSON body from req.body once express.json() is switched on, so a small API takes a few lines instead of sixty.
Apprentice · Node.js · REST API · Updated
After this lesson you can
- Make an Express app that answers GET requests with app.get and res.json
- Read a JSON body in a POST route with express.json() and req.body, and answer 201 with res.status
Key takeaways
- npm install express adds Express to a project, and express() makes an app that holds your routes.
- app.get(path, handler) is a route. Express calls the handler only for a GET request to that path, and answers 404 for any address no route matches.
- res.json(data) turns data into JSON, sets the Content-Type header and sends it, with the status code 200 unless you choose another with res.status.
- A POST route reads the request's JSON body from req.body, but only after app.use(express.json()). Without it, req.body is undefined.
- res.status(201).json(newItem) answers "created" and sends the new item back, so the app can see its new id.
Most Node APIs you'll meet at work, in tutorials and in job interviews are built with Express. When a phone app lists products, saves a sign-up or loads a feed from a Node server, there's a good chance an Express route answered it. This lesson builds your first one, and you'll write routes like it in every chapter from here on.
The Rolling Dice board game café wants its customers to check which games are on the shelf before they come in. Routing by Hand, and Why Frameworks Exist showed what that costs with node:http alone: an if for every endpoint, a body reader, and about sixty lines for three addresses. Express takes over that repeated work.
Installing Express
Make a folder for the café's API and give it a package.json holding { "type": "module" }, the way the earlier lessons did. Then, in VS Code's terminal, inside that folder:
npm install express
added 65 packages, and audited 66 packages in 784ms
31 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Express is one package, and it brings the packages it uses along with it. package.json now lists it under dependencies as "express": "^5.3.0" (read "caret 5.3.0": any 5.x version from 5.3.0 up). This course uses Express 5. Many examples online were written for Express 4, and most of their code works unchanged; the two differences you'll meet are how a path pattern is written, shown in Route and Query Parameters, and errors in async routes, covered in Error Handling and Consistent Error Responses.
A first route
express() makes an app: the object that holds your routes and runs the server. A route pairs a method and a path with the function that answers them. Make server.js:
import express from "express";
const app = express();
const games = [
{ id: 1, title: "Harbor Lights", minPlayers: 2, maxPlayers: 4, minutes: 45, available: true },
{ id: 2, title: "Moon Mice", minPlayers: 3, maxPlayers: 6, minutes: 20, available: false },
{ id: 3, title: "Tile Town", minPlayers: 1, maxPlayers: 2, minutes: 30, available: true },
];
app.get("/games", (req, res) => {
res.json(games);
});
app.listen(3100, () => {
console.log("The café's API is listening on http://localhost:3100");
});
Start it with node --watch server.js, so Node restarts it every time you save:
The café's API is listening on http://localhost:3100
app.get("/games", handler) reads "on a GET to /games, call this function". The handler gets the same req and res you used with node:http, with extra methods added by Express. app.listen makes the server and starts it, in one call.
Sending JSON with res.json
res.json(games) does what took three calls by hand: it turns the data into JSON text, sets the Content-Type header and ends the response. In a cafe.http file, send GET http://localhost:3100/games with REST Client. The top of the answer:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
The body is the three games as JSON. The status is 200 because you didn't choose another. Send GET http://localhost:3100/snacks and Express answers 404 Not Found with a small HTML page that says Cannot GET /snacks: no route matched, so Express sent the 404 you used to write at the bottom of the handler yourself.
A POST route and req.body
When a customer donates a game, the café's app sends it in a POST request's body. Express doesn't read bodies until you ask it to. express.json() reads a JSON body and puts the data on req.body, and app.use(...) switches it on for every request. Add these under const app = express();:
app.use(express.json());
app.post("/games", (req, res) => {
const { title, minPlayers, maxPlayers, minutes } = req.body;
const game = { id: games.length + 1, title, minPlayers, maxPlayers, minutes, available: true };
games.push(game);
res.status(201).json(game);
});
The first line of the handler takes the four values out of the body, and in the new object, title on its own is short for title: title. res.status(201) chooses the status code (201: done, I made it, and here it is), and .json(game) sends the new game back, so the app learns its id. Add the request to cafe.http, below a ### line:
POST http://localhost:3100/games
Content-Type: application/json
{ "title": "Dragon's Picnic", "minPlayers": 3, "maxPlayers": 5, "minutes": 60 }
HTTP/1.1 201 Created
{"id":4,"title":"Dragon's Picnic","minPlayers":3,"maxPlayers":5,"minutes":60,"available":true}
GET /games now lists four games. The new game lives in the games array, so it's gone when the server restarts; Module 3 keeps data in a database.
When req.body is undefined
Leave out app.use(express.json()) and send the same POST. Express answers 500 Internal Server Error, and the terminal says why:
TypeError: Cannot destructure property 'title' of 'req.body' as it is undefined.
Nothing read the body, so req.body is undefined, and the handler can't take values out of it. Put app.use(express.json()) back above the routes. A body that isn't valid JSON, such as { title: Lantern }, now gets 400 Bad Request from express.json() itself, before your handler runs.
Check yourself
2 questions to try on the lesson page.
So what
A route is one line that names a method and a path, and res.json answers it, so the café's three endpoints fit in a few lines, and every Express API you read from now on is built from exactly these pieces.