Einen Body lesen
Teil des Abschnitts Express-Grundlagen der Node.js-Journey von Coddy. Lektion 13 von 20.
Eine POST-Anfrage sendet Daten in ihrem Body, und Express liest den Body nicht, solange du es nicht dazu aufforderst.
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 fragt nach etwas; POST sendet etwas, das erstellt werden soll. express.json() ist Middleware, die jeden JSON-Body in req.body einliest. Ohne sie ist req.body undefined. Eine Route, die etwas erstellt, antwortet mit Status 201 und dem, was sie erstellt hat.
Prüfe den Body, bevor du ihn speicherst. Ein fehlendes Feld ist ein Fehler des Clients, also antworte mit Status 400 und speichere nichts.
Aufgabe
EinfachPOST /api/recipesmit{ "title", "tags" }fügt ein Rezept mit einer neuen ID hinzu und antwortet mit201und dem Rezept.- Kein
title:400mit{ "error": "A recipe needs a title" }.
Sende einen POST mit einem Body, dann GET /api/recipes und anschließend einen POST ohne Titel.
Probier es selbst
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'));
const escapeHtml = (text) =>
text
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
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') sendet reinen Text, sodass jeder Titel in einer eigenen Zeile erscheint.
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');
});
Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Express-Grundlagen
3Middleware
Dein erstes Middleware