Hapijs – 为所有请求添加cookie
使用Hapijs Node框架,我想确保每个请求都存在一个特定的cookie。 如果它不存在,我想创build它。 我想这样做,而不是手动添加该cookie到每个reply
。 例如,像这样的东西:
server.ext('onPreHandler', function (request, reply) { console.log(`state: ${JSON.stringify(request.state)}`) // state == null request.state['my_cookie'] = request.state.my_cookie || 'my data' return reply.continue(); }); server.route({ method: 'GET', path: '/', handler: function(request, reply) { // includes `my_cookie` reply(`Cookies: ${JSON.stringify(request.state)}`); } }) // cookie does not exist in the browser
将该cookie添加到回复中,但需要在应用程序中添加每个回复。
server.route({ method: 'GET', path: '/', handler: function(request, reply) { reply(`Cookies: ${JSON.stringify(request.state)}`).state('my_cookie', 'my_data'); } }) // cookie now exists in the browser
如何确保将Cookie添加到所有请求中,而无需在每个回复中手动添加Cookie?
hapi为您提供了开箱即用的function。
起初,你需要准备一个特定的cookie的服务器:
const Hapi = require('hapi') // create new server instance const server = new Hapi.Server() server.state('session', { ttl: 1000 * 60 * 60 * 24, // 1 day lifetime encoding: 'base64json' // cookie data is JSON-stringified and Base64 encoded })
之后,您可以使用reply
界面设置您的Cookie。 这可以在路由处理程序或扩展请求生命周期的插件中。
扩展请求lifecylce (插件是一个很好的用例)
下面的示例代码扩展了hapi的请求生命周期,并在每个请求上处理
server.ext('onRequest', function (request, reply) { if (!request.state.cookie_name) { reply.state('session', {your: 'cookie_data'}) } reply.continue() })
路由处理器
server.route({ method: 'GET', path: '/', config: { handler: function (request, reply) { const cookie = { lastVisit: Date.now() } reply('Hello Future Studio').state('session', cookie) } } })
像这样读取cookie:
const cookie = request.state.session
您可以在本指南中阅读更多有关Cookie以及如何保持各种请求状态的信息 。
希望有所帮助!
我最终能够与server.ext
做到这一点。
server.ext('onPreHandler', function (request, reply) { request.state.my_cookie || reply.state('my_cookie', 'my value') reply.continue(); });