Menu
CoddyTech

החלפה באמצעות PUT

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

טופס עריכה שולח בחזרה את המשימה כולה, את כל השדות בבת אחת. PUT פירושו „להחליף את המשאב בזה”, ולכן גוף הבקשה חייב להיות מלא.

PATCH /api/invoices/7  { "paid": true }               → paid changes
PUT   /api/invoices/7  { "amount": 90, "paid": true } → invoice 7 replaced
PUT   /api/invoices/7  { "paid": true }               → 400: amount missing

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

const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };
challenge icon

אתגר

קל

טופס עריכה שולח את כל המשימה בחזרה בבת אחת. הוסיפו נתיב PUT שמחליף משימה בתוכן שהלקוח שולח.

  1. ב־routes/tasks.js, הוסיפו PUT /api/tasks/:id. גוף הבקשה חייב להכיל את שני השדות, למשל { "title": "Book the big room", "done": true }.
  2. החליפו את title ואת done של המשימה בערכים שבגוף הבקשה. השאירו את id ואת createdAt כפי שהם במשימה השמורה; לעולם אל תיקחו אותם מגוף הבקשה. השיבו עם סטטוס 200 ועם המשימה כולה:
    { "id": 2, "title": "Book the big room", "done": true, "createdAt": "2026-03-03T10:30:00.000Z" }
  3. אם בגוף הבקשה חסר title או done, השיבו עם סטטוס 400 ועם { "error": "PUT needs every field: title and done" }, ואל תשנו דבר. שדה חסר רק אם הוא כלל לא מופיע בגוף הבקשה: "done": false הוא ערך תקף.
  4. אם אין משימה עם המזהה הזה, השיבו עם סטטוס 404 ועם { "error": "Task not found" }, כמו בנתיבים האחרים.

נסו זאת: PUT /api/tasks/2 עם { "title": "Book the big room", "done": true } מחזיר 200 ואת המשימה שלמעלה. לאחר מכן, PUT /api/tasks/2 עם { "done": true } בלבד מחזיר 400, ו־GET /api/tasks/2 עדיין מציג "Book the big room". PUT /api/tasks/99 עם שני השדות מחזיר 404.

נסו בעצמכם

import { Router } from 'express';
import { nextId, tasks } from '../store.js';

const router = Router();

router.get('/', (req, res) => {
    res.json(tasks);
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    res.json(task);
});

router.post('/', (req, res) => {
    const { title } = req.body ?? {};
    if (!title) {
        return res.status(400).json({ error: 'title is required' });
    }
    const task = { id: nextId(), title, done: false, createdAt: new Date().toISOString() };
    tasks.push(task);
    res.status(201).location(`/api/tasks/${task.id}`).json(task);
});

router.patch('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    const { title, done } = req.body ?? {};
    if (title !== undefined) task.title = title;
    if (done !== undefined) task.done = done;
    res.json(task);
});

router.delete('/:id', (req, res) => {
    const index = tasks.findIndex((t) => t.id === Number(req.params.id));
    if (index === -1) {
        return res.status(404).json({ error: 'Task not found' });
    }
    tasks.splice(index, 1);
    res.status(204).end();
});

export default router;
quiz iconבחנו את עצמכם

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

כל השיעורים ביחידה REST APIs

תרגלו בעצמכם: Express אונליין