昨天我們用 http 模組 開發了一個簡易的伺服器和 API。
在過程中,你應該會發現一些狀況:
if (req.url === ...)
,很麻煩。POST
body 要自己解析,程式碼又臭又長。因此,我們需要一個框架來幫忙,
而 Express.js 正是目前 最受歡迎、最輕量的 Node.js Web 框架。
它能幫你處理好一堆「基礎設施」,讓開發者能更專注在業務邏輯上:
mkdir express-app && cd express-app
npm init -y
npm install express
建立 app.js
:
import express from "express";
const app = express();
const port = 3000;
// 定義路由
app.get("/", (req, res) => {
res.send("Hello from Express");
});
// 啟動伺服器
app.listen(port, () => {
console.log(`伺服器運行中:http://localhost:${port}`);
});
執行:
node app.js
打開瀏覽器 → http://localhost:3000
輸出:
Hello from Express
應用程式 (app)
express()
建立一個伺服器應用程式。路由 (routes)
定義不同網址與 HTTP 方法的處理邏輯,例如:
app.get("/about", (req, res) => res.send("關於我們"));
中間件 (middleware)
🧑💻 Client (Browser / App)
│ 發送請求 (method + url + headers + body)
▼
🌐 Express.js App
┌───────────────────────────────┐
│ 1️⃣ Middleware (中間件) │
│ - 解析 JSON、表單資料 │
│ - 驗證、紀錄 log │
└───────────────────────────────┘
▼
┌───────────────────────────────┐
│ 2️⃣ Route Handler (路由處理器) │
│ - 判斷 GET/POST/PUT/DELETE │
│ - 執行邏輯,準備回應資料 │
└───────────────────────────────┘
▼
┌───────────────────────────────┐
│ 3️⃣ Response (回應) │
│ - res.status(code) │
│ - res.send() / res.json() │
└───────────────────────────────┘
▼
📥 Client 收到回應(HTML / JSON / 純文字)
app.get("/", (req, res) => {
res.send("🏠 首頁");
});
app.get("/about", (req, res) => {
res.send("ℹ️ 關於我們");
});
app.get("/api/time", (req, res) => {
res.json({ now: new Date().toISOString() });
});
Express 內建的 express.json()
中間件,可以解析 JSON body:
app.use(express.json());
app.post("/api/echo", (req, res) => {
const data = req.body;
res.json({ received: data });
});
測試API, 可直接在 VsCode 終端機切換成 bash
模式 或 用 PostMan 發送 api
curl -X POST http://localhost:3000/api/echo \
-H "Content-Type: application/json" \
-d '{"name": "Howard", "msg": "Hello Express"}'
回應:
{
"received": {
"name": "Howard",
"msg": "Hello Express"
}
}
let notes = [];
app.get("/notes", (req, res) => {
res.json(notes);
});
app.post("/notes", (req, res) => {
const note = req.body.note;
notes.push(note);
res.json({ message: "新增成功", notes });
});
測試:
curl -X POST http://localhost:3000/notes \
-H "Content-Type: application/json" \
-d '{"note":"學習 Express"}'
回應:
{
"message": "新增成功",
"notes": ["學習 Express"]
}
今天我們正式進入 Express.js 的世界,體驗到這個框架帶來的便利。
透過 Express,我們輕鬆建立了基礎伺服器、設計路由,甚至還打造了一個簡單的 記事本 API。
在這過程中你應該會感受到:
http
模組細節煩惱明天將進一步深入 Express 路由與中間件 (Middleware) 的設計,
並學習如何將程式碼 模組化拆分,讓專案更好維護與擴充。