gpt4 book ai didi

json - 通过json发送expressjs cookie

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:48 25 4
gpt4 key购买 nike

我在express api引用中看到了数据

expressjs api reference for cookie

在文档中,cookie可以以JSON形式发送 res.cookie('cart', { items: [1,2,3] });

所以我开始尝试,当我使用字符串时,cookie 工作得很好,但不是 JSON 格式。

   res.cookie('cookietmp',{test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.send('test cookie: ' + req.cookies.cookietmp)

这是我的代码

和我的浏览器显示

   test cookie: [object Object]

我的浏览器似乎不知道格式是 JSON 之类的,我该如何解决它?

最佳答案

这是一个对象文字,不是 JSON。 JSON 是一种序列化格式,但您重新尝试设置为 cookie 值的不是字符串。您会在浏览器中看到 '[object Object]',因为这就是 Object.toString返回。

您,程序员,需要使用 JSON.stringify 将该对象转换为 JSON :

var cookieValue = JSON.stringify({test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.cookie('cookietmp', cookieValue);

关于json - 通过json发送expressjs cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com