What Express Does
- Routing — path, method, regex matching
- Middleware — composable request/response pipeline
- Request/response — enhanced req/res objects
- Error handling — centralized error middleware
- Static files —
express.static()built in - Template engines — Pug, EJS, Handlebars via
app.engine() - JSON parsing —
express.json()middleware - Cookies/sessions — via cookie-parser and express-session
- CORS — via cors middleware
- Express 5 — native async error handling (upcoming)
Architecture
Middleware stack: each app.use() adds a function to the pipeline. Request enters, flows through middleware in order, and hits the matching route handler. Router is a mini-app with its own middleware and routes. Error middleware has 4 arguments (err, req, res, next).
Self-Hosting
# Production
NODE_ENV=production node server.js
# PM2
npm i -g pm2
pm2 start server.js -i max
pm2 startup && pm2 save
# Docker
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
CMD ["node", "server.js"]Key Features
- Minimal and unopinionated
- Middleware-based architecture
- Huge middleware ecosystem
- Template engine support
- Static file serving
- HTTP utility methods
- Easy to learn
- Express Generator for scaffolding
- Works with any Node.js version
Comparison
| Framework | Speed | Opinionated | TS |
|---|---|---|---|
| Express | OK | No | via @types |
| Fastify | Fast | Slightly | Yes |
| Hono | Fast | No | Yes |
| Koa | OK | No | via @types |
| NestJS | OK (Express/Fastify) | Yes | Yes |
常见问题 FAQ
Q: Express 过时了吗? A: 没有。Fastify、Hono 性能更好,但 Express 生态最大、教程最多、中间件最丰富。很多生产应用还在用而且很稳定。Express 5 正在开发中。
Q: TypeScript 支持?
A: 用 @types/express 有完整类型。很多项目用 ts-node 或 tsx 开发。
Q: 错误处理? A: Express 4 需要 try-catch 包装 async handler 或用 express-async-errors。Express 5 原生支持 async 抛错自动进入 error middleware。
来源与致谢 Sources
- Docs: https://expressjs.com
- GitHub: https://github.com/expressjs/express
- License: MIT