我想在 Hapi.js 中对我的路由实现 X-Authorization。因此,当我发出请求时,我将创建一个 X-Auth header ,并且我希望 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
访问路由处理程序中的请求 header ,如下所示:
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 })
}
})
如果您需要更多详细信息,可以在 how to access request headers in hapi 上的本教程中阅读更多内容.
此外,如果您需要检查每个传入请求的 X-Authorization
header ,则 create a dedicated plugin 会更有效。 .
希望有帮助!
关于javascript - Hapi.js -- 设置 X-Authorization header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39769650/