Menu
CoddyTech

Asynchrone Routen

Teil des Abschnitts Express-Grundlagen der Node.js-Journey von Coddy. Lektion 18 von 20.

Ein Array ist weg, wenn der Server neu startet. Eine Datei bewahrt die Daten.

import { readFile } from 'node:fs/promises';

app.get('/api/forecast', async (req, res) => {
    const text = await readFile('data/forecast.json', 'utf8');
    res.json(JSON.parse(text));
});

Eine Route kann eine async-Funktion sein, die mit await wartet, hier auf readFile aus node:fs/promises. Express 5 überwacht das Promise, das die Route zurückgibt: Wird es abgelehnt, weil die Datei fehlt oder ihr JSON fehlerhaft ist, wird der Fehler wie bei einem Throw an deinen Fehler-Handler weitergegeben.

Ohne await erhältst du ein Promise statt der Daten, und res.json(promise) sendet {}. Die neue data/recipes.json enthält die vier Rezepte.

challenge icon

Aufgabe

Einfach
  • Jede Route in routes/recipes.js liest die Rezepte bei jeder Anfrage aus data/recipes.json.
  • POST speichert die neue Liste mit writeFile zurück.

Füge ein Rezept hinzu und sende dann GET /api/recipes, GET /api/recipes/5 und GET /api/recipes/99.

Probier es selbst

import express from 'express';
import { recipes } from '../data.js';

const router = express.Router();

// Jeder Tag genau einmal, in alphabetischer Reihenfolge.
router.get('/tags', (req, res) => {
    const tags = new Set(recipes.flatMap((recipe) => recipe.tags));
    res.json([...tags].sort());
});

router.get('/', (req, res) => {
    res.json(recipes);
});

router.get('/: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);
});

router.post('/', (req, res) => {
    const { title, tags } = req.body;
    if (!title) {
        res.status(400).json({ error: 'A recipe needs a title' });
        return;
    }
    const recipe = { id: recipes.length + 1, title, tags: tags ?? [] };
    recipes.push(recipe);
    res.status(201).json(recipe);
});

router.get('/:id/scale', (req, res) => {
    const recipe = recipes.find((r) => r.id === Number(req.params.id));
    if (!recipe) {
        res.status(404).json({ error: 'No such recipe' });
        return;
    }
    const by = Number(req.query.by);
    if (!Number.isFinite(by) || by <= 0) {
        res.status(400).json({ error: 'Scale by a positive number' });
        return;
    }
    if (!recipe.servings) {
        throw new Error(`Recipe ${recipe.id} has no servings`);
    }
    res.json({ title: recipe.title, servings: recipe.servings * by });
});

export default router;
quiz iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Express-Grundlagen