Hapi.js – 设置X-Authorization标头
我想在Hapi.js中对我的路由实施X-Authorization。 所以当我提出请求时,我会创build一个X-Auth头文件,并且希望Hapi在允许执行一些代码之前检查它:
基于Hapi documentaiton的这个代码示例,我该如何实现它?
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'] } });
您可以使用request
对象的headers
属性来获取X-Authorization
值。 但是,它应该是request.headers['x-authorization']
(全部小写)。
有关文档,请参阅http://hapijs.com/api#request-properties 。
“为什么请求头名称应该是小写”的原因是:在Node.js中, request
对象属于类http.IncomingMessage
的头名称是小写的。 有关更多信息,请参阅https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_message_headers 。
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
标头,则创build专用插件将会非常有效。
希望有所帮助!