Menu
CoddyTech

Rezept des Tages

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

Die Rezeptbox erhält ein Rezept des Tages: den ganzen Tag lang dasselbe Rezept für alle, morgen ein anderes. Das Datum bestimmt es, und mit ?date= kannst du jeden beliebigen Tag ausprobieren.

new Date('2026-03-01') ist Mitternacht UTC an diesem Tag. Sein Tag des Jahres wird ab dem 31. Dezember gezählt, daher ist der 1. Januar Tag 1: (date - Date.UTC(year, 0, 0)) / 86400000, denn ein Tag hat 86.400.000 Millisekunden. Ein Text, der kein Datum ist, ergibt ein ungültiges Datum, dessen getTime() NaN ist.

Füge die Route in server.js oberhalb des 404-Handlers hinzu. Wähle aus den Rezepten in data/recipes.json aus, so wie es die API tut, damit ein Rezept, das jemand veröffentlicht, das Rezept des Tages sein kann: Exportiere loadRecipes aus routes/recipes.js und verwende await dafür.

challenge icon

Aufgabe

Einfach
  • GET /api/today?date=2026-03-01 liefert recipes[day % recipes.length] als JSON zurück, wobei recipes aus loadRecipes() stammt und day der Tag des Jahres ist.
  • Kein date: heute.
  • Ein Datum, das sich nicht parsen lässt: 400 mit { "error": "Use a date like 2026-03-01" }.

Sende zweimal ?date=2026-03-01 und dann ?date=soon.

Probier es selbst

import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter from './routes/recipes.js';
import reviewsRouter from './routes/reviews.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.json());

app.use(express.static('public'));

const escapeHtml = (text) =>
    text
        .replaceAll('&', '&')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');

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 steht.
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.use('/api/recipes', recipesRouter);
app.use('/api/recipes/:id/reviews', reviewsRouter);

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.use((req, res) => {
    if (req.path.startsWith('/api/')) {
        res.status(404).json({ error: 'Not found' });
        return;
    }
    res.status(404).send('<h1>Page not found</h1><p><a href="/">Back to Recipe Box</a></p>');
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).json({ error: 'Something went wrong' });
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

Alle Lektionen in Express-Grundlagen