Tampa
Tampa

Reputation: 78254

Newbie with Node JS how to set and get a cookie

I am a newbie with nodejs coming from python.

Below is my standard script for setting and getting cookies in tornado.

if not self.get_cookie('mdi'):
            self.cookie_id=str(uuid4())
            self.set_cookie('mdi', self.cookie_id, domain='mdi.com',expires_days=365*2)
        else:
            self.cookie_id = self.get_cookie('mdi')

What would be the equivalent in NodeJS. I use uuid4 to create cookie id's in python.

Thanks

Upvotes: 1

Views: 468

Answers (1)

Ruben Verborgh
Ruben Verborgh

Reputation: 3665

You might want to use a Web framework for node, such as Express (but there are others).

Express offers cookie functionality with res.cookie. You can do stuff like:

app.get('/', function(req, res){
  res.cookie('rememberme', 'yes',
             { expires: new Date(Date.now() + 900000), httpOnly: true });
});

Then you can read it back like this:

app.use(express.cookieParser());

app.get('/', function(req, res){
  console.log(req.cookies.rememberme);
});

Finally, you can clear it with:

res.clearCookie('rememberme');

Upvotes: 1

Related Questions