Bolboa Bolboa - 1 month ago 9
Node.js Question

Cookie not set (undefined) node js

I am making a

POST
request to my server and sending a token. I want to save this token into a cookie.

I have the following...

app.post('/saveToken', function(req, res){
console.log(req.body.token);
res.cookie('cart', {token:req.body.token, httpOnly: true});
console.log(req.cookies.cart);
})


So
req.body.token
is received. I can see it when I do
console.log
. But when I
console.log(req.cookies.cart)
I get
undefined
. I have no idea why.

I also have the following, which renders my actual app. I'm not sure if this interfering with the cookie but I will add it anyways...

app.get('*', function(req, res){
res.sendFile(path.resolve('public/index.html'));
});

Answer

req.cookies contains the cookies that were sent with the original request.

res.cookie() sets a header that asks the browser to send that cookie next time, but it does not modify req.