החלפה באמצעות PUT
חלק מהיחידה REST APIs במסלול ה-Node.js של Coddy. שיעור 5 מתוך 18.
טופס עריכה שולח בחזרה את כל המשימה, את כל השדות בבת אחת. PUT פירושו "החלף את המשאב בזה", ולכן גוף הבקשה חייב להיות מלא.
PATCH /api/invoices/7 { "paid": true } → paid changes
PUT /api/invoices/7 { "amount": 90, "paid": true } → a new invoice 7
PUT /api/invoices/7 { "paid": true } → 400: amount missingבקשת PUT שחסר בה שדה מחזירה 400: החלפה בחשבונית חלקית תאבד את הסכום. שדות שבבעלות השרת, כמו id וזמן היצירה, מגיעים מהגרסה הישנה, לעולם לא מגוף הבקשה:
const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };אתגר
קלPUT /api/tasks/:idמחליף אתtitleואתdoneבערכים שבגוף הבקשה ומחזיר את המשימה עם קוד 200.idו־createdAtנשארים כפי שהיו.titleאוdoneחסרים: 400. מזהה לא מוכר: 404.
שלחו PUT /api/tasks/2 עם { "title": "Book the big room", "done": true }, ולאחר מכן עם { "done": true }.
נסו בעצמכם
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);
});
router.delete('/:id', (req, res) => {
const index = tasks.findIndex((t) => t.id === Number(req.params.id));
if (index === -1) {
return res.status(404).json({ error: 'Task not found' });
}
tasks.splice(index, 1);
res.status(204).end();
});
export default router;
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.
כל השיעורים ביחידה REST APIs
1משאבים ופעלים
משאבים וכתובות URLיצירה באמצעות POST