昨天我已經用 Express 建立了 GET /todos(讀取) 和 POST /todos(新增)。
今天要把剩下的 更新 (PUT) 和 刪除 (DELETE) 補上,讓 Todo API 變得完整。
昨天的 app.js
已經有一個暫存陣列:
let todos = [
{ id: 1, task: "學 Node.js", done: false },
{ id: 2, task: "寫鐵人賽文章", done: true }
];
今天就在這基礎上新增兩個 API。
用 req.params
來取得路由上的 id
,再搭配 req.body
更新資料。
// 更新 Todo
app.put("/todos/:id", (req, res) => {
const id = parseInt(req.params.id, 10);
const { task, done } = req.body;
let todo = todos.find(t => t.id === id);
if (!todo) {
return res.status(404).json({ error: "找不到這筆 Todo" });
}
if (task !== undefined) todo.task = task;
if (done !== undefined) todo.done = done;
res.json(todo);
});
用 filter
把指定的資料移除。
// 刪除 Todo
app.delete("/todos/:id", (req, res) => {
const id = parseInt(req.params.id, 10);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
return res.status(404).json({ error: "找不到這筆 Todo" });
}
const deleted = todos.splice(index, 1);
res.json(deleted[0]);
});
curl -X PUT http://localhost:3000/todos/1 \
-H "Content-Type: application/json" \
-d '{"done": true}'
輸出:
{ "id": 1, "task": "學 Node.js", "done": true }
curl -X DELETE http://localhost:3000/todos/2
輸出:
{ "id": 2, "task": "寫鐵人賽文章", "done": true }
再次查詢:
curl http://localhost:3000/todos
輸出:
[
{ "id": 1, "task": "學 Node.js", "done": true }
]
今天把 更新 和 刪除 完成之後,Todo API 就有完整的 CRUD 功能了。
雖然現在資料只是存在記憶體陣列裡(重啟就會消失),但整體 API 架構已經成形。
最大的收穫是:
req.params
可以拿路由上的參數(像 /todos/:id
)req.body
則是接收使用者傳來的資料(要先用 express.json()
)404
或 400
來避免回傳怪怪的結果看到自己做出一個可以新增、修改、刪除的 API,真的超有成就感 ✨