Hapijs - 为所有请求添加cookie

时间:2017-04-25 15:18:56

标签: javascript node.js cookies hapijs

使用Hapijs Node框架,我想确保每个请求都存在某个cookie。如果它不存在,我想创建它。我想在不手动将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?

2 个答案:

答案 0 :(得分:2)

hapi为您提供了开箱即用的功能。

首先,您需要为特定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的request lifecycle,并在每次请求时处理

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

您可以在cookies and how to keep states across requests, in this guide上阅读更多内容。

希望有所帮助!

答案 1 :(得分:1)

我最终能够使用server.ext执行此操作。

server.ext('onPreHandler', function (request, reply) {
    request.state.my_cookie || reply.state('my_cookie', 'my value')

    reply.continue();
});