如何将参数传递到路由处理程序前 - hapi.js

How to pass params into route handler pre - hapi.js

我正在使用路由处理程序 pre。我想通过路由器的权限所以我的想法是检查登录用户是否有权限?当我直接传递 parm 时,它会抛出错误。

路由选择

 server.route({ 
     method: 'GET', 
     path: '/getUser', 
     config: {
         handler: User.getUser, 
         pre: [
              { method: Activity.checkVal(1) }
         ]
     }
 });

函数调用

exports.checkVal = function(parm, request, reply) {
    Jwt.verify(request.headers.authorization.split(' ')[1],  Config.key.privateKey, function(err, decoded) {    
        var permissions = permissionsSet();
        if(permissions.indexOf(request.pre.val) > -1)
            return reply().continue();
        else
            reply(Boom.forbidden( "You don't have permission." ));
    });

}

错误

Error: Invalid routeConfig options (getUser)

有没有办法将参数传递到路由中?

您可以通过给 pre 对象一个 assign 属性:

来为 request.pre 对象分配属性
 server.route({ 
      method: 'GET', 
      path: '/getUser', 
      config: {
          handler: User.getUser, 
          pre: [
               { method: Activity.checkVal(1), assign: 'someVar' }
          ]
      }
  });

然后在你的路由处理程序中:

 User.getUser = function (request, reply) {
      console.log(request.pre.someVar);
 }

(假设您的 Activity.checkVal(1) returns 函数具有通常的 request, reply 签名)

根据您的编辑:

我建议您创建一个闭包;像这样:

exports.checkVal = function(parm) {

    return function preHandler(request, reply) {

        Jwt.verify(request.headers.authorization.split(' ')[parm], Config.key.privateKey, function(err, decoded) {    
            var permissions = permissionsSet();
            if(permissions.indexOf(request.pre.val) > -1)
                return reply().continue();
            else
                reply(Boom.forbidden( "You don't have permission." ));
        });
    }
}

在配置对象上使用路由的 "permission level" 解决了我的问题。

var checkVal = function (request, reply) {

     var permissionLevel = request.route.settings.app.permissionLevel;

     ... // decide whether to allow
};

server.route({
  config: {
      app: {
        permissionLevel: 1  // "permission level" for this route
    },
    pre: [
        checkVal   
    ]
  },
  method: 'GET',
  path: '/',
  handler: function (request, reply) {

    ... // do whatever
  }
});

这里是link供参考https://github.com/hapijs/hapi/issues/2652#event-360912937