express

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Express

Express

Express is the standard web framework for Node.js. Express 5 (2025) finally stabilizes modern features like Promise support in middleware, removing the need for
express-async-errors
.
Express是Node.js的标准Web框架。Express 5(2025版)终于稳定了诸如中间件中的Promise支持等现代特性,不再需要使用
express-async-errors

When to Use

适用场景

  • Microservices: Lightweight and fast.
  • REST APIs: The standard for building JSON APIs in Node.
  • Learning: The best way to learn how HTTP works in Node.
  • 微服务:轻量且高效。
  • REST API:Node.js中构建JSON API的标准方案。
  • 学习:了解Node.js中HTTP工作原理的最佳途径。

Quick Start (Express 5)

快速开始(Express 5)

javascript
import express from "express";
const app = express();

// Express 5 handles async errors automatically!
app.get("/", async (req, res) => {
  const user = await db.getUser(); // If this throws, Express catches it.
  res.json(user);
});

app.listen(3000);
javascript
import express from "express";
const app = express();

// Express 5会自动处理异步错误!
app.get("/", async (req, res) => {
  const user = await db.getUser(); // 如果此处抛出错误,Express会自动捕获。
  res.json(user);
});

app.listen(3000);

Core Concepts

核心概念

Middleware

中间件

Functions that have access to
req
,
res
, and
next
. They form a pipeline.
Log -> Auth -> BodyParse -> RouteHandler
.
能够访问
req
res
next
的函数,它们构成一个处理管道,流程为:
日志 -> 认证 -> 解析请求体 -> 路由处理器

Routing

路由

app.get()
,
app.post()
. Simple regex-based routing.
使用
app.get()
app.post()
,基于正则表达式的简单路由机制。

Best Practices (2025)

2025年最佳实践

Do:
  • Upgrade to Express 5: Native Promise support is a game changer for cleaner code.
  • Use
    helmet
    : Security headers are mandatory.
  • Structure properly: Don't put everything in
    app.js
    . Use
    express.Router()
    .
Don't:
  • Don't stick to CommonJS: Express 5 supports ESM. Use
    import
    .
  • Don't use
    body-parser
    separate package
    : Use
    express.json()
    (included since v4, standard in v5).
建议做
  • 升级到Express 5:原生Promise支持能极大简化代码,提升整洁度。
  • 使用
    helmet
    :安全头是必备配置。
  • 合理架构:不要将所有代码都放在
    app.js
    中,使用
    express.Router()
    进行拆分。
不建议做
  • 不要固守CommonJS:Express 5支持ESM,使用
    import
    语法。
  • 不要单独使用
    body-parser
    :使用
    express.json()
    (自v4版本已内置,v5中为标准配置)。

References

参考资料