跳轉到

4.1 用 Express 建立第一個 API#

Express:最流行的 Web 框架#

Node 內建的 http 模組寫 API 太囉嗦(見 2.2 節)。Express 把路由、中介層、回應處理都簡化了,是全世界最流行的 Node.js Web 框架。

建立 API 的完整流程#

第一步:初始化專案並安裝 Express

mkdir my-api && cd my-api
npm init -y
npm install express

第二步:建立 app.js

import express from "express";

const app = express();
app.use(express.json());   // 讓 Express 能解析 JSON 請求主體

// GET:查詢
app.get("/api/todos", (req, res) => {
  res.json(todos);
});

// GET:帶路徑參數
app.get("/api/todos/:id", (req, res) => {
  const todo = todos.find(t => t.id === Number(req.params.id));
  if (!todo) {
    return res.status(404).json({ error: "找不到" });
  }
  res.json(todo);
});

// POST:新增
app.post("/api/todos", (req, res) => {
  const todo = { id: Date.now(), title: req.body.title, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});

// DELETE:刪除
app.delete("/api/todos/:id", (req, res) => {
  todos = todos.filter(t => t.id !== Number(req.params.id));
  res.status(204).end();
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`http://localhost:${PORT}`));

let todos = [{ id: 1, title: "學 Node", done: false }];

第三步:啟動與測試

node app.js
# http://localhost:3000

另開一個終端機測試:

curl http://localhost:3000/api/todos
curl -X POST http://localhost:3000/api/todos -H "Content-Type: application/json" -d '{"title": "買牛奶"}'

核心概念:路由與中介層#

路由(Route):app.get(路徑, 處理函式),按 HTTP 方法與路徑分派:

app.get("/path", handler);     // 讀
app.post("/path", handler);    // 新增
app.put("/path", handler);     // 整體更新
app.delete("/path", handler);  // 刪除

中介層(Middleware):請求進來先經過的一層層處理函式:

app.use(express.json());          // 解析 JSON 請求主體
app.use((req, res, next) => {     // 自訂中介層:記 log
  console.log(`${req.method} ${req.url}`);
  next();   // 呼叫 next() 交給下一層
});

常用模式:

res.json(data);              // 回傳 JSON(200)
res.status(404).json({...}); // 自訂狀態碼
res.status(201).json(x);     // 建立成功
req.params.id;               // 路徑參數 /todos/:id
req.query.q;                 // 查詢字串 ?q=xxx
req.body;                    // 請求主體(需 express.json())

RESTful API 的狀態碼慣例:200 成功、201 建立成功、204 刪除成功、400 請求錯誤、404 找不到、500 伺服器錯誤。