通过json发送expressjs cookie
我在ExpressAPI参考中看到了这些数据 在文档中,cookie可以作为JSON通过json发送expressjs cookie,json,node.js,cookies,express,Json,Node.js,Cookies,Express,我在ExpressAPI参考中看到了这些数据 在文档中,cookie可以作为JSONres.cookie('cart',{items:[1,2,3]})发送 所以我开始尝试,当我使用字符串时,cookie工作得很好,但不是JSON格式 res.cookie('cookietmp',{test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true}); res.send('test cookie: ' + req.cookies
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]'
,因为这是返回的内容
作为程序员,您需要使用以下命令将该对象转换为JSON:
您的cookie设置正确。问题是您正在响应
对象上设置cookie,然后检查过时的请求
对象以获取cookie的值。更新响应
不会更新传入的请求
:
console.log(req.cookies.cookieTmp) // '[object Object]'
res.cookie('cookietmp',{test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.send('test cookie: ' + req.cookies.cookietmp)
console.log(req.cookies.cookieTmp) // '[object Object]'
console.log(res.get('Cookie')) // 'cookieTmp={test: ['test1', 'test2']}` (or urlencoded version of this).
但是在expressjs文档中的示例中,您不需要使用JSON。设置cookie之前进行字符串化,为什么?res.send('test cookie:'+req.cookies.cookietmp)
执行内部req.cookies.cookietmp.toString()
生成[object object]
。您不需要序列化cookie,res.cookie方法足够智能,可以处理序列化和反序列化。尝试发送res.send('testcookie:'+JSON.stringify(req.cookies.cookietmp))
现在,我使用res.send('testcookie:'+JSON.stringify(req.cookies.cookietmp))
我得到测试cookie:“[对象对象]”
,这是不对的。@LiJung只要您尝试将对象存储为cookie,它就会自动强制为字符串。当然JSON.stringify(req.cookies.cookietmp)
不会做任何有用的事情,因为如果您试图从req.cookies.cookietmp
中恢复原始对象,那就太晚了。在将对象设置为cookie之前,必须对其进行JSON字符串化。在文档中,似乎我不需要在设置之前对JSON进行字符串化。我知道stringify可以工作,但我希望只发送JSON格式的cookie,我该怎么做?(很抱歉问题中的链接错误,我稍后会修复它。)
console.log(req.cookies.cookieTmp) // '[object Object]'
res.cookie('cookietmp',{test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.send('test cookie: ' + req.cookies.cookietmp)
console.log(req.cookies.cookieTmp) // '[object Object]'
console.log(res.get('Cookie')) // 'cookieTmp={test: ['test1', 'test2']}` (or urlencoded version of this).