在開發 API 的過程中,除了功能實現與資料正確性之外, 穩定性與防護性 也是關鍵。假設沒有任何限制,惡意或大量的請求可能會導致:
Rate Limit 指的是 在一定時間內,限制使用者的請求次數。
例如:
在固定時間段內(例如 1 分鐘),限制最大請求數。
缺點:如果用戶在時間邊界狂發請求,可能造成「尖峰流量」。
以時間為連續軸計算請求數,更平滑地控制流量。
我們可以使用 express-rate-limit 套件。
安裝
npm install express-rate-limit
使用範例
import express from "express";
import rateLimit from "express-rate-limit";
const app = express();
// 設定每個 IP 每分鐘最多 10 次請求
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 分鐘
max: 10, // 最大 10 次
message: {
status: 429,
error: "Too many requests, please try again later."
},
});
// 套用到所有路由
app.use(limiter);
app.get("/", (req, res) => {
res.send("API 正常運作");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
現在,當同一個 IP 在 1 分鐘內請求超過 10 次,就會收到 429 Too Many Requests 錯誤。