Menu
CoddyTech

削除

CoddyのNode.jsジャーニー「REST API」セクションの一部。レッスン 4/18。

削除後は、クライアントに表示するものが何も残りません。その場合の応答は204 No Contentです。リクエストは成功し、本文は空です。

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

2回目のリクエストではイベント5が見つからないため、不明なIDに対するGETと同様に404を返します。配列から項目を削除するには、findIndexで位置を探します。一致するものがない場合は-1が返され、spliceでその項目を取り除きます。

events.splice(index, 1);   // index の位置にある要素を 1 つ削除する
res.status(204).end();     // ステータスを返し、本文は返さない
challenge icon

チャレンジ

簡単
  • DELETE /api/tasks/:id はタスクを削除し、本文なしで 204 を返します。
  • 不明な ID には、{ "error": "Task not found" } とともに 404 を返します。

DELETE /api/tasks/3 を 2 回送信し、その後 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 APIのすべてのレッスン