【问题标题】:How to set a cookie inside a route handler using the state() method on the response object?如何使用响应对象上的 state() 方法在路由处理程序中设置 cookie?
【发布时间】:2019-06-08 23:08:41
【问题描述】:

我试图在我的响应对象之后使用 state 方法在我的路由处理程序下创建一个 cookie,但 cookie 没有以任何方式出现。即使在 hapijs 网站上粘贴许多示例也不起作用。

我的 index.js:

const Hapi = require('hapi')

const server = new Hapi.Server
({
  host: 'localhost',
  port: 8000
})

server.route({
  method: 'GET',
  path: '/',
  config: {
    handler: (request, h) => {
      return h.response(`Cookie!`).state('cookie-name', 'cookie-value');
    }
  }
})


async function start() {
  await server.start();
  console.log(`Server started at ${ server.info.uri }`);
}

start();

我希望 'cookie-name' 出现在开发者控制台中的 'name' 下,以及 'cookie-value' 作为 'value' 出现。什么都没有显示,我在刷新本地主机时收到此错误消息:

Debug: internal, implementation, error 
    Error: Invalid cookie value: [object Object]
    at exports.Definitions.internals.Definitions.internals.Definitions.format (/Users/cayden/Documents/egghead/introduction-to-node-servers-with-hapijs/lessons/12-hapi.js-managing-state-with-cookies/node_modules/hapi/node_modules/statehood/lib/index.js:361:24)
    at process._tickCallback (internal/process/next_tick.js:68:7)

以我的方式建立 cookie 与我在他们的网站上看到的一个示例很接近。我错过了什么导致我的代码不生成 cookie?

【问题讨论】:

    标签: javascript hapijs


    【解决方案1】:

    要合法设置cookie,首先需要通过调用server.state(name, [options]) 方法配置cookie,其中name 是cookie 名称。 options 是配置该 cookie 的对象。

    将这行代码添加到您现有的代码中:

    
     server.state("cookie-name", {
            ttl: null,
            isSecure:  false,
            isHttpOnly: true,
            clearInvalid: false,
            strictHeader: true
      });
    
      server.route({
         method: 'GET',
         path: '/',
         config: {
             handler: (request, h) => {
                return h.response(`Cookie!`).state('cookie-name', 'cookie-value');
               }
           }
       })
    

    希望现在您可以在开发浏览器中看到 cookie 及其价值。

    【讨论】:

    • 啊,谢谢,在查看这里之前,我最终创建了 server.state(),但由于某种原因缺少“isSecure: false”行,因为没有它,我收到了错误消息。感谢您的帮助:)
    • 欢迎 :)。是的,因为isSecure: true 表明 cookie 只能在 https 上运行,因此如果不是安全连接,浏览器将不会显示 cookie
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多