Back to Final Review Hub 返回期末复习中心
Day 3 - Final Review Day 3 - 期末复习

⏱️ Express Async & Middleware ⏱️ Express 异步与中间件

Mastering Timers, Routing Order, and API Testing 掌握定时器、路由顺序和 API 测试

🚨 The "Order Matters" Trap 🚨 “顺序至关重要”陷阱

Why did our API return 404?为什么我们的 API 返回 404?

In Express, code runs top-to-bottom. If you define a "catch-all" (404 handler) BEFORE your routes, it intercepts everything! 在 Express 中,代码从上到下运行。如果你在路由之前定义了一个“捕获所有”(404 处理程序),它会拦截所有请求!

// ❌ WRONG: Middleware blocks routes// ❌ 错误:中间件阻塞路由 app.use((req, res) => res.status(404).json(...)); // 🛑 STOP HERE app.get('/v1/users', ...); // 💀 Never reached!
// ✅ CORRECT: Routes first, then 404 trap// ✅ 正确:先定义路由,再定义 404 捕获 app.get('/v1/users', ...); // 🏃 Runs first app.use((req, res) => res.status(404).json(...)); // 🕸️ Catches anything missed

🛡️ Essential Middleware 🛡️ 核心中间件

1. cors()

Allows frontend (browser) to talk to backend on different ports. Without this, browser blocks requests. 允许(浏览器)前端与不同端口的后端通信。没有这个,浏览器会阻止请求。

2. express.json()

Parses incoming JSON payloads in req.body. Without this, req.body is undefined. 解析 req.body 中的传入 JSON 载荷。没有这个,req.body 为 undefined。

3. morgan('dev')

Logger. Prints "GET /v1/users 200" to your terminal. Crucial for debugging. 日志记录器。在终端打印 "GET /v1/users 200"。对调试至关重要。

⚡ Async Safety & Timers ⚡ 异步安全与定时器

When using setTimeout in Express (e.g. for scheduled deletion), you must catch errors INSIDE the callback. 在 Express 中使用 setTimeout(例如用于计划删除)时,必须在回调内部捕获错误。

// 💥 CRASH RISK: Express cannot catch this!// 💥 崩溃风险:Express 无法捕获这个! setTimeout(() => { throw new Error("Oops"); // Kills server (Curl 7) }, 1000); // 🛡️ SAFE PATTERN// 🛡️ 安全模式 const timer = setTimeout(() => { try { deleteSomething(); } catch (err) { console.error("Timer failed safely:", err); } }, 1000); // Store timer to allow cancellation! timers[id] = timer;

Memory Management内存管理

When clearing data (RESET), you MUST also clearTimeout() all active timers. Otherwise, they might run later and try to delete non-existent data! 清除数据(重置)时,必须同时 clearTimeout() 所有活动定时器。否则,它们稍后可能会运行并尝试删除不存在的数据!

🧪 Testing Strategy 🧪 测试策略