Menu
CoddyTech

דף החיפוש

חלק מהיחידה יסודות Express במסלול ה-Node.js של Coddy. שיעור 20 מתוך 20.

דף חיפוש הוא טופס, והשרת משיב לו כמו לכל בקשת GET אחרת.

<form action="/books" method="get">
    <input name="author">
    <button>Find</button>
</form>

שליחת הטופס הזה מעבירה את הדפדפן אל /books?author= ואחריו מה שהוקלד בשדה ששמו author. הנתיב קורא את הערך מתוך req.query. כתיבת המילה בחזרה בתור value של השדה משאירה אותה גלויה לאחר החיפוש; היא הגיעה מהמבקר, לכן יש לבצע לה escaping.

challenge icon

אתגר

קל
  • GET /search?q=soup מציג דף עם טופס GET (השדה q, שנשלח אל /search) וקישורים לכותרות שמכילות את המילה, ללא תלות באותיות גדולות או קטנות, מתוך loadRecipes().
  • אין התאמה: No recipes found.
  • השדה שומר את המילה, כשהיא מסומנת ב-escape.

פתחו את /search בתצוגת הדף וחפשו SOUP, ואז pizza.

נסו בעצמכם

import express from 'express';
import { randomUUID } from 'node:crypto';
import { recipes } from './data.js';
import recipesRouter, { loadRecipes } 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('&', '&amp;')
        .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') שולח טקסט פשוט, כך שכל כותרת מופיעה בשורה נפרדת.
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('/api/today', async (req, res) => {
    const date = req.query.date ? new Date(req.query.date) : new Date();
    if (Number.isNaN(date.getTime())) {
        res.status(400).json({ error: 'Use a date like 2026-03-01' });
        return;
    }
    const day = Math.floor((date - Date.UTC(date.getUTCFullYear(), 0, 0)) / 86400000);
    const recipes = await loadRecipes();
    res.json(recipes[day % recipes.length]);
});

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');
});

כל השיעורים ביחידה יסודות Express