4

Im trying to set cookies for my website using node.js and express.js. Heres a simplified version of my code:

var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());

app.post('/testCookies', function(req, res) {
   console.log(req.cookies); //empty object
   res.cookie('username', 'test');
   console.log(req.cookies); //still an empty object

   res.end();
});

I tried POSTing twice in case the cookies somehow get set after the request (im not very familiar with cookies yet) but it doesn't change anything. The console does not show any errors.

3
  • I'm not familiar with your stack but can't you simply set a cookie value like that : req.cookies.test = "somestring"; ? Commented Apr 7, 2016 at 7:50
  • According to this stackoverflow question and this blogpost you have to use res.cookie(...) Commented Apr 7, 2016 at 7:59
  • 1
    See Alex's Answer, thats what I am using as well. Commented Apr 7, 2016 at 8:02

1 Answer 1

1

You could use req.session() instead. That would let you do

req.session.username = "test";

See the docs here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.