Menu
CoddyTech

Xóa tài nguyên

Thuộc phần REST API trong hành trình Node.js của Coddy. Bài học 4 trên 25.

Sau khi xóa, không còn gì để hiển thị cho ứng dụng khách. Câu trả lời cho trường hợp này là 204 No Content: yêu cầu đã thành công và phần thân trống.

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

Yêu cầu thứ hai không tìm thấy sự kiện 5, nên trả về 404 như yêu cầu GET cho một id không tồn tại. Để xóa một phần tử khỏi mảng, hãy tìm vị trí của nó bằng findIndex, phương thức này trả về -1 khi không có phần tử nào khớp, rồi xóa phần tử đó bằng splice:

events.splice(index, 1);   // Xóa 1 phần tử tại chỉ số index
res.status(204).end();     // Một mã trạng thái và không có phần nội dung
challenge icon

Thử thách

Dễ
  • DELETE /api/tasks/:id xóa tác vụ và trả về mã 204, không có nội dung.
  • ID không tồn tại sẽ trả về mã 404 cùng { "error": "Task not found" }.

Gửi DELETE /api/tasks/3 hai lần, rồi gửi GET /api/tasks.

Tự làm thử

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;

Tất cả bài học trong REST API

Tự luyện tập: Playground Express