Menu
CoddyTech

ה-Middleware הראשון שלך

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

יש פעולות שנדרשות בכל בקשה, כמו כתיבת שורה ליומן, והעתקתן לכל נתיב לא תסתיים לעולם.

let visits = 0;

app.use((req, res, next) => {
    visits++;
    next();
});

פונקציה שמועברת אל app.use היא תוכנת ביניים: Express מריצה אותה בכל בקשה, לפי הסדר שבו היא נוספה, לפני הנתיבים שמתחתיה. היא מקבלת ארגומנט שלישי, next. קריאה ל-next() מעבירה את הבקשה הלאה, אל מה שמגיע אחר כך. תוכנת ביניים שאינה משיבה ואינה קוראת ל-next() משאירה את הבקשה בהמתנה לנצח.

גם express.static מהפרק הקודם היא תוכנת ביניים: היא משיבה כשהיא מוצאת קובץ וקוראת ל-next() כשהיא לא מוצאת.

challenge icon

אתגר

קל

הוסף תווכה שמדפיסה את השיטה ואת הנתיב של כל בקשה, כמו GET /recipes/2.

שלח GET /recipes/2 ואת GET /nope, ואז קרא את המסוף.

נסו בעצמכם

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

const app = express();

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') שולח טקסט פשוט, כך שכל כותרת מופיעה בשורה נפרדת.
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');
});
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

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