Menu
CoddyTech

מחרוזות שאילתה

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

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

app.get('/books', (req, res) => {
    const { author } = req.query;
    res.send(author ? 'Books by ' + author : 'All books');
});

מחרוזת השאילתה היא החלק בכתובת ה-URL שמופיע אחרי ?, ו-Express מציב אותה ב-req.query. הקריאה GET /books?author=Austen מחזירה את req.query.author === 'Austen'. אם אין ?, הערך הוא undefined. כמה אפשרויות מחוברות באמצעות &: /books?author=Austen&year=1813.

פרמטר נתיב הוא חלק מהנתיב ושמו מציין פריט אחד. אפשרות שאילתה מסננת או ממיינת רשימה, וניתן להשמיט אותה.

challenge icon

אתגר

קל
  • GET /recipes?tag=vegan מציג רק את שמות המתכונים עם התג הזה, אחד בכל שורה.
  • בלי tag, הוא מציג את כל השמות.

שלחו GET /recipes?tag=vegan, GET /recipes?tag=dessert ו-GET /recipes.

נסו בעצמכם

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

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// type('text') שולח טקסט רגיל, כך שכל כותרת מופיעה בשורה נפרדת.
app.get('/recipes', (req, res) => {
    res.type('text').send(recipes.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('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

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

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