iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Modern Web

現在就學Node.js系列 第 11

Express.js 入門 - Day11

  • 分享至 

  • xImage
  •  

昨天我們用 http 模組 開發了一個簡易的伺服器和 API。

在過程中,你應該會發現一些狀況:

  • 路由判斷要自己寫 if (req.url === ...),很麻煩。
  • 處理 POST body 要自己解析,程式碼又臭又長。
  • 設定 Header、狀態碼必須重複撰寫,不易維護。

因此,我們需要一個框架來幫忙,

Express.js 正是目前 最受歡迎、最輕量的 Node.js Web 框架

它能幫你處理好一堆「基礎設施」,讓開發者能更專注在業務邏輯上:

  • 簡化 路由管理
  • 提供好用的 中間件機制
  • 支援 快速建 API 與後端應用

建立 Express 專案

1. 初始化專案

mkdir express-app && cd express-app
npm init -y

2. 安裝 Express

npm install express

Hello 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 

Express 的核心概念

  1. 應用程式 (app)

    • express() 建立一個伺服器應用程式。
  2. 路由 (routes)

    • 定義不同網址與 HTTP 方法的處理邏輯,例如:

      app.get("/about", (req, res) => res.send("關於我們"));
      
  3. 中間件 (middleware)

    • 在請求與回應之間處理資料,例如驗證、日誌、body 解析。

Express 請求處理流程

🧑‍💻 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() });
});

POST 請求

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"
  }
}

📝 迷你記事本 API

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) 的設計,

並學習如何將程式碼 模組化拆分,讓專案更好維護與擴充。


上一篇
用HTTP、fs與path模組 — 打造靜態檔案伺服器和API - Day10
系列文
現在就學Node.js11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言