Menu
CoddyTech

קבצים סטטיים

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

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

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

express.static('assets') מגיש את הקבצים שבתיקייה assets בשמותיהם: assets/logo.png משיב לבקשת GET /logo.png. שם התיקייה אינו חלק מכתובת ה-URL. Express קובע את סוג התוכן לפי הסיומת: text/css עבור .css, image/png עבור .png. נתיב שאין בו קובץ ממשיך אל הנתיבים שלך.

app.use מוסיף פונקציה שרצה עבור כל בקשה; הפרק הבא עוסק בפונקציות האלה. כעת יש בפרויקט שלך תיקיית public עם גיליון סגנונות.

challenge icon

אתגר

קל
  • הגש את תיקיית public, כך שהבקשה GET /style.css תחזיר את הקובץ.
  • קשר אליו מדף הבית באמצעות <link rel="stylesheet" href="/style.css">.

פתח את / בתצוגת הדף, ואז שלח את הבקשות GET /style.css ו־GET /missing.css.

נסו בעצמכם

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

const app = express();

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(`<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.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});

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