الحذف
جزء من قسم واجهات REST API في رحلة Node.js على Coddy. الدرس 4 من 25.
بعد الحذف، لا يتبقى شيء لعرضه على العميل. والإجابة عن ذلك هي 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); // احذف عنصرًا واحدًا عند index
res.status(204).end(); // حالة بدون محتوىالتحدي
سهل- يحذف
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 API
1الموارد والأفعال
الموارد وعناوين URLالإنشاء باستخدام POST4المتصفحات والإصدارات والإعدادات
ما هو Originالسماح لـ Origin آخرCORSصفحة تستدعي APIتدرّب بنفسك: Playground لـ Express