Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cookie in express.js appear j: prefix

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?

like image 753
Alicia Brandon Avatar asked Jul 03 '16 07:07

Alicia Brandon


2 Answers

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.

like image 183
MortenTZ Avatar answered Sep 29 '22 22:09

MortenTZ


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))

like image 31
lava Avatar answered Sep 29 '22 21:09

lava