我正在尝试使用 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?
要合法设置cookie,首先需要通过调用server.state(name, [options])
name为cookie名称的方法来配置cookie。而选项是对象来配置该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 及其值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句