Menu
CoddyTech

使用 PUT 替换

本课属于 Coddy Node.js 学习旅程的“REST API”单元。第 5 课,共 25 课。

编辑表单会一次性发回整个任务的所有字段。PUT 表示“用这个替换资源”,因此请求正文必须完整。

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 missing

如果 PUT 缺少字段,就会返回 400:用半张发票替换会导致金额丢失。服务器管理的字段,例如 id 和创建时间,来自旧版本,而不是请求正文:

const { id, issuedAt } = invoices[index];
invoices[index] = { id, amount, paid, issuedAt };
challenge icon

挑战

简单

编辑表单会一次性发送整个任务。添加一个 PUT 路由,用客户端发送的内容替换任务。

  1. 在 routes/tasks.js 中,添加 PUT /api/tasks/:id。请求体必须包含两个字段,例如 { "title": "Book the big room", "done": true }。
  2. 将任务的 title 和 done 替换为请求体中的值。保留存储任务中的 id 和 createdAt,绝不要从请求体中获取它们。返回状态码 200 和整个任务:
    { "id": 2, "title": "Book the big room", "done": true, "createdAt": "2026-03-03T10:30:00.000Z" }
  3. 如果请求体缺少 title 或 done,则返回状态码 400 和 { "error": "PUT needs every field: title and done" },并且不做任何更改。只有当字段完全不在请求体中时,才算缺少该字段:"done": false 是一个有效值。
  4. 如果没有任务的 ID 与该 ID 匹配,则返回状态码 404 和 { "error": "Task not found" },与其他路由相同。

试试看:使用 { "title": "Book the big room", "done": true } 调用 PUT /api/tasks/2,会返回 200 和上面的任务。然后,仅使用 { "done": true } 调用 PUT /api/tasks/2,会返回 400,而 GET /api/tasks/2 仍会显示 "Book the big room"。使用两个字段调用 PUT /api/tasks/99,会返回 404。

亲手试试

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;
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

REST API中的所有课

自己练习: Express 在线编辑器