概述
Express 是 Node.js 生态中最广泛使用的 Web 框架之一,以中间件链组织请求处理,路由和扩展生态成熟。
核心 API
express():创建支持路由和中间件的应用实例。Router:创建模块化路由处理器,把端点拆分到不同文件。Middleware:注册请求处理、日志和错误处理中间件。app.get:为指定路径注册 GET 处理器。app.listen:在指定端口启动 HTTP 服务器。
import express from 'express';
const app = express();
app.use(express.json());
app.get('/healthz', (_req, res) => res.sendStatus(200));
app.use((err, _req, res, _next) => {
console.error(err);
res.status(500).json({ error: 'internal error' });
});
app.listen(3000);
使用注意
Express 5 会自动捕获 async 错误;Express 4 需要包装器。限制请求体大小,配置安全响应头,并在反向代理后正确设置 trust proxy,否则限流和 IP 记录会失真。
验证方式
用 supertest 断言路由、JSON 解析、404 与错误中间件的状态码和响应体。