Reading a Body
Part of the Express Basics section of Coddy's Node.js journey. Lesson 15 of 23.
A POST request sends data in its body, and Express does not read the body unless you ask it to.
app.use(express.json());
app.post('/api/loans', (req, res) => {
const { bookId, member } = req.body;
res.status(201).json({ bookId, member, due: '2026-11-08' });
});GET asks for something; POST sends something to be created. express.json() is middleware that reads every JSON body into req.body. Without it req.body is undefined. A route that creates something answers 201 with what it made.
Check the body before you save it. A missing field is the client's mistake, so answer 400 and save nothing.
Challenge
EasyVisitors can add their own recipes. A program sends the new recipe as JSON in the body of a POST request, and your API saves it.
- In
server.js, addexpress.json()with the otherapp.uselines, above the routes, so that a JSON body arrives inreq.body. - Add a route for POST requests to
/api/recipes. It readstitleandtagsfrom the body, for example{"title": "Miso Soup", "tags": ["vegan", "soup"]}. - It builds the new recipe with the next number id: the four recipes have ids 1 to 4, so the first new one gets 5. It keeps the title and tags it was sent. If no
tagscame, use an empty list,[]. - It adds the recipe to the
recipesarray, soGET /api/recipeslists it. Then it responds with status 201 and the new recipe as JSON:{"id": 5, "title": "Miso Soup", "tags": ["vegan", "soup"]} - When the body has no
title, it saves nothing and responds with status 400 and this JSON:{"error": "A recipe needs a title"}
Try it: Press Run. Pick POST in the method picker, type /api/recipes as the path, and put {"title": "Miso Soup", "tags": ["vegan", "soup"]} in the body box. You should see status 201 and the recipe with "id": 5. Pick GET and send /api/recipes: five recipes, with Miso Soup last. Then POST {"tags": ["dinner"]} to /api/recipes: status 400 and {"error":"A recipe needs a title"}. GET /api/recipes still lists five recipes.
Try it yourself
import { escapeHtml } from './html.js';
import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
const app = express();
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use((req, res, next) => {
res.set('X-Request-Id', randomUUID());
next();
});
app.use(express.static('public'));
app.get('/', (req, res) => {
const items = recipes.map((r) => `<li><a href="/recipes/${r.id}">${escapeHtml(r.title)}</a></li>`);
res.send(`<link rel="stylesheet" href="/style.css"><h1>Recipe Box</h1><ul>${items.join('')}</ul>`);
});
// type('text') sends plain text, so each title shows on its own line.
app.get('/recipes', (req, res) => {
const { tag } = req.query;
const list = tag ? recipes.filter((recipe) => recipe.tags.includes(tag)) : recipes;
res.type('text').send(list.map((recipe) => recipe.title).join('\n'));
});
app.get('/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).send('No such recipe');
return;
}
res.send(recipe.title);
});
app.get('/api/recipes', (req, res) => {
res.json(recipes);
});
app.get('/api/recipes/:id', (req, res) => {
const recipe = recipes.find((r) => r.id === Number(req.params.id));
if (!recipe) {
res.status(404).json({ error: 'No such recipe' });
return;
}
res.json(recipe);
});
app.get('/about', (req, res) => {
res.send('Recipe Box collects family recipes.');
});
app.get('/menu', (req, res) => {
res.redirect(301, '/recipes');
});
app.get('/menu/:id', (req, res) => {
res.redirect(301, `/recipes/${req.params.id}`);
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Express Basics
3Middleware
Your First MiddlewarePractice on your own: Express playground