2016-09-29 45 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

可以使用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瞭解更多信息。

2

高致病性禽流感,可以通過使用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有效。

希望有幫助!