如何在 sails 中的 myRequestLogger 中间件中获取目标控制器和操作名称



我希望在 sails http.js myRequestLogger 自定义中间件中请求路由控制器和操作名称。

尝试req.options.controllerreq.options.action

类似于

下面的中间件可以记录控制器/操作,中间件必须在router之前,并在请求事件end记录打印。

控制器/操作

仅打印,如果定义了控制器/操作,在静态文件,404等的情况下,可能无法定义。

middleware: {
  order: [
    ...
    'logController',
    'router',
    ...
  ],
  logController: function(req, res, next) {
    req.on("end", function() {
      sails.log.info('logController##Options2:', req.options); // This contains controller/action along with other data
    });
    sails.log.info('logController##Options1:', req.options); // undefined
    next();
  },
}

原木:

RequestLogger##Options1: undefined
...
RequestLogger##Options2: { detectedVerb: { verb: '', original: '/', path: '/' },
  skipRegex: [],
  _middlewareType: 'CORS HOOK: sendHeaders',
  controller: 'user',
  action: 'list',
  locals: { layout: 'layout' } }

请记住,一个请求可以匹配多个路由,例如

'/user/list': 'UserController.list',
'user/:id': 'UserController.detail',

控制器可以调用其第三个参数next移动到下一个匹配的控制器/操作。

最新更新