I saw the data in express api reference
expressjs api reference for cookie
in the document, cookie can send as JSON res.cookie('cart', { items: [1,2,3] });
so I started to try, cookie worked well when I use string, but not in JSON format.
res.cookie('cookietmp',{test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.send('test cookie: ' + req.cookies.cookietmp)
this is my code
and my browser display
test cookie: [object Object]
it seems like my browser doesn't know the format is JSON or something, how can I solve it?
That's an object literal, not JSON. JSON is a serialization format, but what you'retrying to set as the cookie value is not a string. You see '[object Object]'
in the browser because that's what Object.toString
returns.
You, the progammer, need to convert that object into JSON using JSON.stringify
:
var cookieValue = JSON.stringify({test: ['test1', 'test2']}, { maxAge: 900000, httpOnly: true});
res.cookie('cookietmp', cookieValue);