我是nodejs新手,我正在使用hapijs制作一个api来处理mi网站的一些功能,我希望能够制作一个像api/*这样的基本url,并制作以api/开头的所有其他url通过一些验证,但只执行一次,这就是我到目前为止所拥有的:
server.route([
{
method: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
path: "/api/*",
handler: function(request, reply){
is_authorized = auth(request.raw.req.headers['Authorization']);
if(!is_authorized){
reply(response.generate_json(null, 'no autorizado', 'UNAUTHORIZED')).code(401);
}
}
}
]);
但它不起作用,当我调用任何其他网址(如 api/sockets/whatever)时,即使未经授权,它也会传递......有什么方法可以在 hapijs 中实现此目的吗?
最佳答案
你必须在预处理程序钩子(Hook)上使用
server.ext('onPreHandler', (request, reply) => {
if(request.path.startsWith("/api/"))
{
is_authorized = auth(request.raw.req.headers['Authorization']);
if(!is_authorized)
{
reply(response.generate_json(null, 'no autorizado', 'UNAUTHORIZED')).code(401);
}
else
{
return reply.continue();
}
}
else
{
return reply.continue();
}
});
如果您需要任何进一步的信息。很高兴为您提供帮助
关于node.js - 使用 hapijs 制作基本路由过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163377/