Menu
CoddyTech

מחיקה

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

אחרי מחיקה לא נשאר שום דבר להציג ללקוח. התשובה לכך היא 204 No Content: הבקשה הצליחה והגוף ריק.

DELETE /api/events/5   →  204 No Content
DELETE /api/events/5   →  404 Not Found

הבקשה השנייה לא מוצאת אירוע 5, ולכן מחזירה 404 כמו בקשת GET עבור מזהה לא מוכר. כדי להסיר פריט ממערך, מצאו את המיקום שלו באמצעות findIndex, שמחזירה -1 כשאין התאמה, והוציאו אותו באמצעות splice:

events.splice(index, 1);   // הסר פריט 1 במיקום index
res.status(204).end();     // סטטוס ללא גוף
challenge icon

אתגר

קל
  • DELETE /api/tasks/:id מסיר את המשימה ומשיב 204 ללא גוף.
  • מזהה לא מוכר משיב 404 עם { "error": "Task not found" }.

שלחו DELETE /api/tasks/3 פעמיים, ואז GET /api/tasks.

נסו בעצמכם

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

export default router;

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