iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
自我挑戰組

《轉職學習日記:JavaScript × Node.js × TypeScript × Docker × AWS ECS》系列 第 14

Day14 - 持續成長學習藍圖 - Node.js(REST API CRUD 設計 II)

  • 分享至 

  • xImage
  •  

昨天我已經用 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。


PUT /todos/:id – 更新 Todo

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);
});

DELETE /todos/:id – 刪除 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]);
});

測試 API

更新 Todo

curl -X PUT http://localhost:3000/todos/1 \
  -H "Content-Type: application/json" \
  -d '{"done": true}'

輸出:

{ "id": 1, "task": "學 Node.js", "done": true }

刪除 Todo

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()
  • 錯誤處理很重要,記得加上 404400 來避免回傳怪怪的結果

看到自己做出一個可以新增、修改、刪除的 API,真的超有成就感 ✨


上一篇
Day13 - 持續成長學習藍圖 - Node.js(REST API CRUD 設計 I)
下一篇
Day15 - 持續成長學習藍圖 - Node.js(連接資料庫 – MongoDB 基礎)
系列文
《轉職學習日記:JavaScript × Node.js × TypeScript × Docker × AWS ECS》16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言