PUT ile Değiştirme
Coddy'nin Node.js Journey'sinin REST API'leri bölümünün bir parçası. Ders 5 / 25.
Düzenleme formu, görevin tamamını, tüm alanları bir kerede geri gönderir. PUT, "kaynağı bununla değiştir" anlamına gelir; bu nedenle gövde eksiksiz olmalıdır.
PATCH /api/invoices/7 { "paid": true } → paid changes
PUT /api/invoices/7 { "amount": 90, "paid": true } → invoice 7 replaced
PUT /api/invoices/7 { "paid": true } → 400: amount missingBir alanı eksik olan PUT isteği 400 yanıtı verir: yarım bir faturayla değiştirmek tutarın kaybolmasına yol açar. Sunucunun yönettiği id ve oluşturulma zamanı gibi alanlar istek gövdesinden değil, eski sürümden gelir:
const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };Görev
KolayBir düzenleme formu tüm görevi tek seferde geri gönderir. İstemcinin gönderdiği değerlerle bir görevi değiştiren bir PUT rotası ekle.
routes/tasks.jsdosyasınaPUT /api/tasks/:idekle. Gövdesinde her iki alan da bulunmalı; örneğin{ "title": "Book the big room", "done": true }.- Görevin
titlevedonealanlarını gövdedeki değerlerle değiştir.idvecreatedAtdeğerlerini kayıtlı görevden al; bunları asla gövdeden alma. 200 durum koduyla görevin tamamını yanıt olarak gönder:{ "id": 2, "title": "Book the big room", "done": true, "createdAt": "2026-03-03T10:30:00.000Z" } - Gövdede
titleveyadoneeksikse 400 durum koduyla{ "error": "PUT needs every field: title and done" }yanıtını gönder ve hiçbir şeyi değiştirme. Bir alan yalnızca gövdede hiç bulunmuyorsa eksiktir:"done": falsegeçerli bir değerdir. - Bu kimliğe sahip bir görev yoksa diğer rotalarda olduğu gibi 404 durum koduyla
{ "error": "Task not found" }yanıtını gönder.
Deneyin: PUT /api/tasks/2 isteği { "title": "Book the big room", "done": true } ile gönderildiğinde 200 ve yukarıdaki görevi döndürür. Ardından PUT /api/tasks/2 isteği yalnızca { "done": true } ile gönderildiğinde 400 döndürür ve GET /api/tasks/2 hâlâ "Book the big room" değerini gösterir. Her iki alanla birlikte gönderilen PUT /api/tasks/99 isteği 404 döndürür.
Kendin dene
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;
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
REST API'leri bölümündeki tüm dersler
1Kaynaklar ve Fiiller
Kaynaklar ve URL'lerPOST ile Oluşturma4Tarayıcılar, Sürümler ve Yapılandırma
Origin NedirBaşka Bir Origin'e İzin VermeCORSAPI'yi Çağıran Bir SayfaKendi başına pratik yap: Express playground