今日筆者將繼續昨天的內容,先暫時不繼續進行網頁專案,而是來介紹一下express中的 router,一個能讓我們將 API 拆分得更乾淨,且維護程式能夠加舒服的小工具。那麼就讓我們直接開始今天的內容吧!
簡單說,Router 是一個可掛載(mount)的「迷你 Express 應用」。它有和 app
相同的 API(get / post / use
等),但只負責某一塊路由邏輯,最後用 app.use('/prefix', router)
掛到主應用上。這種做法可以把程式切得更模組化、好維護。
至於為什麼要使用 Router 呢?它有著下面幾點優勢:
/api/auth/*
)放在同一個檔案/資料夾。index.js
只負責掛載各個 router,閱讀起來清爽。下面是一個幾個最精簡的可執行範例:
// src/server/auth.router.js
import { Router } from 'express';
export const auth = Router();
// 範例:router 級別的 middleware(可做簡單的請求標記)
auth.use((req, _res, next) => { req.requestTime = Date.now(); next(); });
auth.post('/signup', (req, res, next) => {
try {
const { username, password } = req.body;
res.json({ ok: true, username, createdAt: req.requestTime });
} catch (err) { next(err); }
});
auth.post('/login', (req, res) => {
const { username, password } = req.body;
res.json({ message: `Trying to login with account ${username} using password ${password}` });
});
// src/server/index.js
import express from 'express';
import { auth } from './auth.router.js';
const app = express();
app.use(express.json()); // 先解析 JSON,再進入router
app.use('/api/auth', auth); // 掛載 router
// 錯誤:找不到的 API(404)
app.use('/api', (_req, res) => res.status(404).json({ error: 'Not found' }));
// 錯誤處理中介軟體(四個參數,放最後)
app.use((err, _req, res, _next) => {
res.status(500).json({ error: err.message || 'Internal Server Error' });
});
app.listen(3000, () => console.log('API at http://localhost:3000'));
在使用時,有以下幾點是需要注意的:
express.json()
必須在路由之前,否則 req.body
會是 undefined
。Router 也支援像 :id
這樣的參數路徑,Express 會自動把值放到 req.params
:
auth.get('/users/:id', (req, res) => {
res.json({ userId: req.params.id }); // /api/auth/users/42
});
此部份為 Express 官方對於 routing 所提供的基本用法,用起來十分的直覺且容易上手。
參考資料: