了解快速 nodeJs 路由器行为

Understanding express nodeJs router behavior

本文关键字:路由器 nodeJs 了解      更新时间:2023-09-26

此路由工作正常:

router.post('/addlog', multipartMiddleware, function(req,res){
   controller.postLog(req,res);
});

但是如果我像这样更改呼叫:

router.post('/addlog', multipartMiddleware, controller.postLog(req,res));

节点抱怨ReferenceError: req is not defined .控件位于单独的文件中:

exports.postLog = function(req, res, next) {
  console.log(req.body);
  res.status(200).send('OK');
}

为什么?

您立即调用controller.postLog并将该调用的结果传递给router.post

假设您不需要访问this,因为postLog内部controller

router.post('/addlog', multipartMiddleware, controller.postLog);

这会将对postLog函数的引用传递给router.post这是该函数所期望的 - 它需要对函数的引用,以便可以使用请求和响应对象调用该函数。

如果您需要this内部postLog引用controller您可以使用bind生成将在controller上下文中调用的新函数:

router.post('/addlog', multipartMiddleware, controller.postLog.bind(controller));

问题不在于路由器行为,下面是关于 JS 中回调的文章。

http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/