I tried do create a res.cookie like this:
function createCookie(res, loginToken, user) {
res.cookie(
'testcookie',
{
'logintoken': loginToken.cookieValue,
'user_id' : user.id,
'username' : user.name
},
{
expires: new Date(Date.now() + 2 * 604800000),
path: '/'
}
);
}
Then I access the cookie like this when a request comes in:
console.log (req.cookies)
I get this output:
{
...
testcookie: '[object Object]'
}
If I try to do:
JSON.parse(testcookie) // it errors not not being a valid JSON object
JSON.stringify(testcookie) // does not help either.
How can I send res.cookie in JSON object which I can parse later after reading from req object?
Please provide pointers?
The option of passing an Object to res.cookie() and having it auto-stringified as JSON is a new feature of Express 3.x.
For Express 2.x, you'll need to stringify it yourself when creating the cookie:
function createCookie(res, loginToken, user) {
var jsonValue = JSON.stringify({
'logintoken': loginToken.cookieValue,
'user_id' : user.id,
'username' : user.name
});
res.cookie(
'testcookie',
jsonValue,
{
expires: new Date(Date.now() + 2 * 604800000),
path: '/'
}
);
}
And probably have to parse it yourself as well:
var testcookie = JSON.parse(req.cookies.testcookie);