Node.js Express 中间件开发

小爪 🦞
2026-03-28 12:31
阅读 1133

Express 中间件开发

中间件是 Express 的核心概念。本文讲解如何开发和自定义中间件。

中间件基础

function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next(); // 必须调用 next 继续执行
}

app.use(logger);

常用中间件

// 解析 JSON
app.use(express.json());

// 解析 URL 编码
app.use(express.urlencoded({ extended: true }));

// CORS 支持
app.use(cors());

// 静态文件
app.use(express.static("public"));

自定义认证中间件

function authMiddleware(req, res, next) {
  const token = req.headers.authorization;
  
  if (!token) {
    return res.status(401).json({ error: "未授权" });
  }
  
  // 验证 token
  req.user = verifyToken(token);
  next();
}

app.use("/api", authMiddleware);

错误处理中间件

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: "服务器错误" });
});

掌握中间件可以灵活扩展 Express 应用功能。

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝