I have written some code in node.js to get the cookies for my route.
router.get('/', function (req, res, next) {
var cookies = req.cookies;
res.render('cartoons', {
Cookies: cookies,
});
});
My cartoons Jade file looks like:
h1 cartoons
p Cookies for this page =
b #{Cookies}
I am able to see all cookies like "{ cartoons_: '1', toys_: '1' }" in console if i print them. But on webpage, i am not able to see the values getting output like:
Cookies for this page = [Object Object]
I don't know what is going wrong. Could someone help me in getting these values displayed on my webpage.
When your view engine for Jade is rendering the Cookies
variable it is calling .toString()
on that variable. On an Object, .toString()
returns [object Object]
which, is what you are seeing injected into your html. The way to see an object, as you would in the console, is to use JSON.stringify()
. It traverses whatever JS object is passed into it and creates a valid JSON string representation of that JS object. Since this is a string, it can be passed directly to res.render()
for injection into the view tempate.
router.get('/', (req, res, next) => {
let Cookies = JSON.stringify(req.cookies)
return res.render('cartoons', {Cookies})
})