2016-09-29 5 views
1

私はHapi.jsの私のルートにX-Authorizationを実装したいと思います。だから私が要求するとき、私はX-Authヘッダを作成し、コード実行を許可する前にHapiに確認させたい:Hapi.js - X-Authorizationヘッダーを設定

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'] 
} 
}); 

答えて

1

あなたはX-Authorization値を取得するためにrequestオブジェクトのheadersプロパティを使用することができます。ただし、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を参照してください。

2

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 }) 
    } 
}) 

あなたはより多くの詳細が必要な場合は、how to access request headers in hapiに、このチュートリアルで詳細を読むことができます。

さらに、受信リクエストごとにX-Authorizationヘッダーをチェックする必要がある場合は、create a dedicated pluginに効率的です。

希望に役立ちます!

関連する問題