【问题标题】:Hapijs - add cookie to all requestsHapijs - 将 cookie 添加到所有请求
【发布时间】:2017-09-22 17:00:38
【问题描述】:

使用 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?

【问题讨论】:

    标签: javascript node.js cookies hapijs


    【解决方案1】:

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

    首先,您需要为特定的 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 接口设置您的cookies。这可以在路由处理程序或扩展请求生命周期的插件中。

    延长请求生命周期(插件是一个很好的用例)

    下面的示例代码扩展了 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 上阅读更多内容。

    希望有帮助!

    【讨论】:

    • 感谢@MarcusPoehls。这是一个 必须 在每个请求上设置的 cookie。您的解决方案是针对特定请求的。你知道有什么方法可以为每个请求做到这一点吗?
    • 我更新了我的问题,以澄清我要解决的问题。如果您有任何进一步的想法,我很想听听。
    • 啊,我明白了。我要做的是向您的 hapi 服务器注册一个插件,该插件会检查您对给定 cookie 的请求,如果尚未设置,请添加它。我已经用示例代码更新了我的答案。
    【解决方案2】:

    我最终能够通过server.ext 做到这一点。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2021-02-09
      • 2014-07-17
      • 1970-01-01
      相关资源
      最近更新 更多