I'm trying to set cookie using res.cookie like below:
res.cookie('userId',req.user._id); //set cookie here
console.log(req.user._id); //returned correct value, eg abc
then I'm seeing j:"abc" in my cookie, why does this happens?
I know this is a bit late, but I came across this issue myself and have been digging around a bit. It seems they're prefixing any JSON strings with "j:" so they know it's a JSON string when parsing it back. What this basically means is that you have to manually remove the "j:" if you're using some other way of parsing it.
Cookies are encrypted to the client side. You need a cookie-parser to correctly get the user.id from your cookie. See its documentation for use.
According the the Express 4 docs , res.cookie(name, value [, options])
sets a cookie name to a value. The value parameter may be a string or object converted to JSON.
In this instance, req.user._id
is an object so you would set the cookie as res.cookie('userId', JSON.stringify(req.user._id))
So I'm using cookie-parser & express-session on the NodeJS side, ng2-cookies on the client side. I was also expecting to read userId as ie 59bca61b74d1cac10ce50d0c
rather than j:59bca61b74d1cac10ce50d0c
:(
So, rather than have to do some magic on the client side I just did res.cookie('cookieName', cookieValue.toString(), cookieOptions)
and this gave me what I was looking for.
Doing a console.log('cookies', req.cookies)
shows things are fine, although req.headers.cookie shows 2 userId cookies (still testing)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.