Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS set/get/use cookies

Cannot get setted cookies within requests.

I set my cookie with

response.cookie('name', 'My name');

I would like to get my cookie this way, and it worked before, but I changed express configuration, and I don't know what seems to be the problem now.

request.cookies is and empty Object

My express configuration:

var express = require('express'),
    api = require('./routes/api');

var app = express();

app.configure(function () {
   app.set('port', process.env.PORT || 3000);
   app.use(express.favicon());
   app.use(express.logger('dev'));
   app.use(express.json());
   //app.use(express.bodyParser());
   app.use(express.compress()); // New call to compress content
   app.use(express.cookieParser());
   app.use(express.session({secret: 'secret'}));
   app.use(app.router);
   app.use(express.methodOverride());
   //app.use(express.static(__dirname + '/public'));
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
    next();
});

app.configure('development', function () {
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
    app.use(express.errorHandler());
});

Setting Cookie:

exports.singIn = function (req, res) {
    var mail = req.query.mail,
        password = req.query.password;

    return user.find({
        mail: mail
    }).then(function (d) {
        var user = usersData(u);

        res.cookie('mail', user.mail, { maxAge: 900000});
        res.cookie('password', crypted, { maxAge: 900000});
        res.json({ user: user });
        return { user: user }
    }).catch(function () {
        res.json(400, {"error-tag": "error-sing-in"});
        return {"error-tag": "error-sing-in"};
    });
};

Getting Cookie:

exports.account = function (req, res) {
    var mail = req.cookies.mail,
        password = req.cookies.password;
    //here req.cookies is an empty object. I don't know why? 
};
like image 746
puppeteer701 Avatar asked Oct 25 '13 13:10

puppeteer701


People also ask

How do I request cookies in Express?

to get a cookie from an incoming request .. let cookie = req. cookies['cookiename'];

How do I view cookies in node JS?

We can check cookies by visiting localhost:3000/setcookie.

Which property is used to set expiration time of cookies in Express JS?

So, to set expire time to cookies, an object with expire property can be sent which holds the expire time in milliseconds. An alternate approach to set cookie expiration age is to use optional magAge property. res. cookie(name, 'value', {maxAge : 9999});


2 Answers

It's kind of exaggerated to use an extra package ("cookie-parser"), when this is the middleware function you need:

function cookieParser(req, res, next) {
  var cookies = req.headers.cookie;
  if (cookies) {
    req.cookies = cookies.split(";").reduce((obj, c) => {
      var n = c.split("=");
      obj[n[0].trim()] = n[1].trim();
      return obj
    }, {})
  }
  next();
}
app.use(cookieParser);

I couldn't use "cookie-parser" in my graphQL server because it was messing things up.

like image 122
Martin Cup Avatar answered Oct 17 '22 08:10

Martin Cup


An answer for 2017 ..

const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
app.use(cookieParser());

to get a cookie from an incoming request ..

let cookie = req.cookies['cookiename'];

to set a response cookie (this cookie will be sent on all future incoming requests until deletion or expiration) ..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 86400 * 1000, // 24 hours
    httpOnly: true, // http only, prevents JavaScript cookie access
    secure: true // cookie must be sent over https / ssl
});

to delete a response cookie ..

res.cookie('cookiename', 'cookievalue', {
    maxAge: 0
});
like image 22
danday74 Avatar answered Oct 17 '22 07:10

danday74