为什么我的 express 中间件函数中的第 4 个参数仅在特定条件下会破坏它?

Why does the 4th argument in my express middleware function only break it in certain conditions?

提问人:Brenden Baio 提问时间:11/15/2023 更新时间:11/15/2023 访问量:40

问:

我是 node/express 的新手,遇到了一些对我来说很奇怪的事情。如果我在某些中间件函数上包含第 4 个“值”参数,它们将不起作用,而其他函数则有效。我已经阅读了添加第 4 个参数会将其计为错误处理中间件,但我不确定这是否是一回事。这是我读到的: Express.js 中间件额外(第四)参数。 我怀疑这与中间件 1 作为参数传入有关,而中间件 2 被传递到帖子中,但我对它的工作原理感到困惑。任何帮助解释将不胜感激,谢谢。

控制器.js

exports.middleware1  = (req, res, next, val) => {
  if (Number(req.params.id) > tours.length) {
    return res.status(404).json({
      status: 'failed',
      message: 'Invalid ID',
    });
  }
  next();
};

exports.middleware2 = (req, res, next) => {
  if (!req.body.name || !req.body.price) {
    return res.status(400).json({
      status: 'fail',
      message: 'Missing name or price',
    });
  }

  next();
};

路由.js

router.param('id', middleware1) // this one works even if I include the "val" parameter
router.post(middleware2, createPost) // this one wont work if I include the "val" parameter as my 4th parameter
JavaScript 节点.js 表示 REST CRUD

评论

1赞 jonrsharpe 11/15/2023
具有四个参数的函数被视为错误处理中间件 - expressjs.com/en/guide/...

答:

1赞 eekinci 11/15/2023 #1

当您使用中间件函数时,express 需要四个参数:、、、:router.param('id', middleware1)reqresnextval

router.param('id', (req, res, next, val) => {
  next();
});

当您使用中间件函数时,express 只需要三个参数:、、:router.post(middleware2, createPost)reqresnext

router.post((req, res, next, val) => {
  next();
}, createPost);

源: router.param(name, callback)

为路由参数添加回调触发器,其中 name 是参数的名称,callback 是回调函数。尽管 name 在技术上是可选的,但从 Express v4.11.0 开始,不推荐使用此方法

回调函数的参数为:

  • req,请求对象。
  • res,响应对象。
  • next,指示下一个中间件函数。
  • name 参数的值。
  • 参数的名称。

中间件函数可以采用不同数量的参数,中间件函数具有的参数数量决定了其行为。

常规中间件:3 个参数

app.use((req, res, next) => {
  next();
});

错误处理中间件:4 个参数

app.use((err, req, res, next) => {
  res.sendStatus(500);
});