Usuwanie
Część sekcji API REST ścieżki Node.js w Coddy. Lekcja 4 z 18.
Po usunięciu nie pozostaje nic, co można pokazać klientowi. Odpowiedzią na to jest 204 No Content: żądanie powiodło się, a treść odpowiedzi jest pusta.
DELETE /api/events/5 → 204 No Content
DELETE /api/events/5 → 404 Not FoundDrugie żądanie nie znajduje zdarzenia 5, więc zwraca 404, tak jak żądanie GET dotyczące nieznanego identyfikatora. Aby usunąć element z tablicy, znajdź jego pozycję za pomocą findIndex, które zwraca -1, gdy nic nie pasuje, a następnie usuń go za pomocą splice:
events.splice(index, 1); // usuń 1 element pod indeksem index
res.status(204).end(); // status bez treści odpowiedziWyzwanie
ŁatwyDELETE /api/tasks/:idusuwa zadanie i zwraca kod 204 bez treści.- Nieznane id zwraca kod 404 z treścią
{ "error": "Task not found" }.
Wyślij DELETE /api/tasks/3 dwa razy, a następnie GET /api/tasks.
Spróbuj swoich sił
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;
Wszystkie lekcje w sekcji API REST
1Zasoby i czasowniki
Zasoby i URL-eTworzenie za pomocą POST