使用Hapijs Node框架,我想確保每個請求都存在某個Cookie。如果它不存在,我想創建它。我想這樣做,而無需手動將該cookie添加到每個reply
。例如,像這樣:Hapijs - 爲所有請求添加cookie
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?
太棒了,你已經找到了解決方案:) –