happi .js——设置x -授权头

Hapi.js -- Set X-Authorization header

本文关键字:授权 设置 js happi      更新时间:2023-09-26

我想在happi .js中对我的路由实现X-Authorization。因此,当我发出请求时,我将创建一个X-Auth头,我希望Hapi在允许一些代码执行之前检查它:

基于这个来自Hapi文档的代码示例,我如何实现它?
server.route({
method: 'GET',
path: '/hello/{user?}',
handler: function (request, reply) {
    const user = request.params.user ? encodeURIComponent(request.params.user) : 'stranger';
    reply('Hello ' + user + '!');
},
config: {
    description: 'Say hello!',
    notes: 'The user parameter defaults to ''stranger'' if unspecified',
    tags: ['api', 'greeting']
}
});

hapi允许您使用request.headers访问路由处理程序中的请求头,如下所示:

server.route({  
  method: 'GET',
  path: '/hello/{user?}',
  handler: function (request, reply) {
    const headers = request.headers   // <-- get request headers
    const auth = headers['x-authorization']
    // use the auth header value for further processing
    reply({ your: data })
  }
})

如果你需要更多的细节,你可以阅读更多关于如何在hapi中访问请求头的教程。

另外,如果你需要检查X-Authorization头在每个传入的请求,这将是有效的创建一个专门的插件。

希望有帮助!

可以使用request对象的headers属性来获取X-Authorization的值。但是,它应该是request.headers['x-authorization'](全部小写)。

请参考http://hapijs.com/api#request-properties。

"为什么请求头名应该小写"的原因是:在Node.js中,request对象属于http.IncomingMessage类,其头名是小写的。