【问题标题】:How do I request a cookie when server rendering on hapi?服务器在 hapi 上渲染时如何请求 cookie?
【发布时间】:2015-12-16 17:58:06
【问题描述】:

我知道在使用 express 时,可以使用以下代码请求 cookie:

req.get('cookie')

但是,我现在在使用 hapi 服务器请求 cookie 时遇到了一个问题。

请求 cookie 的代码如下:

request.state['COOKIE_NAME']

但是,当服务器渲染我的页面时,我的request.state 始终为空。当客户端请求 cookie 时,没有问题,request.state 填充了 cookie。

在我的服务器文件上,我使用onPreResponse 挂钩如下:

server.ext( 'onPreResponse', ( request, reply ) => {
...
  fetch('http://localhost:3000/api/getcookie', {
    credentials: 'same-origin',
    headers: {'Cookie': request.state['COOKIE_NAME']} // Still empty
  })
...
});

hapi 路线是:

{
  method: 'GET',
  path: '/getcookie',
  config: {
    auth: false
},
  handler: ( request, reply ) => {
    console.log('GET COOKIE ROUTE: ', request.state); // <-- this is empty when server rendering

    reply({
      statusCode: 200,
      message: 'get cookie',
      data: {
        text: request.state
      }
    })
    .code(200);
}

cookie 的设置没有问题,我也可以在客户端上检索它们。问题是当我尝试在服务器上获取 cookie 时。

如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: cookies fetch server-side hapijs


    【解决方案1】:

    你的问题对我来说有点难以理解。你写...

    cookie 的设置没有问题,我也可以在客户端上检索它们。问题是当我尝试在服务器上获取 cookie 时。

    ...但我没有看到任何实际设置 cookie 值的代码。所以我不明白你如何成功地进入客户。并且在服务器onPreResponse 扩展点中使用一些fetch 方法请求相同的路由我也不清楚。

    我写了一个小而完整的例子,它实际上设置了一个 cookie,还利用了onPreResponse 扩展点。

    'use strict';
    
    const Hapi = require('hapi');
    const Path = require('path');
    
    // Create a server with a host and port
    const server = new Hapi.Server();
    server.connection({
      port: 3000
    });
    
    //Define the cookie
    server.state('data', {
        encoding: 'base64json'
    });
    
    // Add the route
    server.route({
      method: 'GET',
      path: '/getcookie',
      handler: function(request, reply) {
    
        const counterState = request.state.data.counter;
        const counter = counterState ? counterState + 1 : 1;
    
        return reply({
          statusCode: 200,
          message: 'get cookie',
          currentState: request.state
        })
        .state('data', {counter: counter}); //<-- You missed to actually SET your cookie!
      }
    });
    
    server.ext( 'onPreResponse', ( request, reply ) => {
    
      //Here you have full access to the original request
      console.log("PreResponse counter value: " + request.state.data.counter);
    
      return reply.continue();
    
    });
    
    // Start the server
    server.start((err) => {
    
      if (err) {
        throw err;
      }
    
      console.log('Server running at:', server.info.uri);
    });
    

    我希望这可以帮助您了解如何在 hapi 中使用 cookie,并以某种方式为您的特定问题提供解决方案。

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2018-04-03
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2018-04-04
      相关资源
      最近更新 更多