You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js/Express中Middleware Function匹配条件后的执行逻辑问询

关于Express中间件验证通过后是否进入路由处理函数的疑问

我正在开发Node.js/Express项目,目前正在研究中间件函数(Middleware Function),以下是我的示例代码:

const authMiddleware = (req, res, next) => {
  if (req.headers.authorization === 'secret-token') {
    next(); // Proceed to the next middleware or route handler
  } else {
    res.status(401).send('Unauthorized');
  }
};

// Using the middleware function for a specific route
app.get('/api/protected', authMiddleware, (req, res) => {
  res.send('Protected route');
});

我想咨询:当条件匹配(即secret-token验证通过,进入if分支)时,是否会进入/api/protected对应的路由处理函数?


是的,当req.headers.authorization等于secret-token时,中间件里的next()会被调用,这会让Express的请求处理流程继续推进,直接进入后续绑定在该路由上的处理函数,也就是你写的(req, res) => { res.send('Protected route'); },最终客户端会收到Protected route的响应。

简单来说,Express路由里的中间件是按顺序执行的:

  • 先运行authMiddleware
  • 中间件调用next()后,就会触发下一个处理逻辑(这里就是目标路由的处理函数)
  • 如果中间件没调用next()而是直接返回了响应(比如else分支的401),后续的路由处理函数就不会被执行

内容的提问来源于stack exchange,提问作者Diana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:53:10