Routing 如何将参数传递到路由处理程序pre-hapi.js中
我正在使用路由处理程序pre。我想从路由器传递权限,所以我的想法是检查登录的用户是否有权限?当我直接通过parm时,它会抛出一个错误 路由Routing 如何将参数传递到路由处理程序pre-hapi.js中,routing,hapijs,Routing,Hapijs,我正在使用路由处理程序pre。我想从路由器传递权限,所以我的想法是检查登录的用户是否有权限?当我直接通过parm时,它会抛出一个错误 路由 server.route({ method: 'GET', path: '/getUser', config: { handler: User.getUser, pre: [ { method: Activity.checkVal(1) }
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." ));
});
}
错误
错误:无效的routeConfig选项(getUser)
是否仍有将参数传递到路由中的方法?您可以通过为
pre
对象指定assign
属性来为请求分配属性。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);
}
(这是假设您的活动。checkVal(1)
返回一个带有通常请求、回复
签名的函数)
编辑后:
我建议您创建一个闭包;大概是这样的:
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." ));
});
}
}
在配置对象上使用路由的“权限级别”修复了我的问题
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
}
});
这是一个供参考的链接你能提供一点关于你想要实现的目标的更多信息吗?也许还有更多的代码。
Activity.checkVal
是一个返回函数的函数吗?是的,但我必须将参数传递给pre函数。我也尝试过赋值,但它期望函数(请求、回复)而不是任何参数,它显示:无效的routeConfig选项然后Activity.checkVal(1)
需要返回具有正确签名的函数。我想我们需要看更多的代码。