express cookie return undefined - node.js

I'm trying to set cookie on express.js but it return undefined.
I've searched many web pages and put express.cookieParser() above app.use(app.router)
but it still can't return the right value.
app.js
app.configure(function(){
var RedisStore = require('connect-redis')(express);
app.use(express.logger());
app.set('view options', { layout: false });
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser({uploadDir: './uploads/tmp'}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: "william", store: new RedisStore }));
//Initialize Passport! Also use passport.session() middleware, to support
//persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
//app.router should be after passportjs
app.use(app.router);
app.use(express.compiler({ src: __dirname + '/public', enable: ['less']}));
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true})
});
app.get('/test', function(req, res) {
res.send('testcookie: ' + req.cookies.cart);
});
the result:
testcookie: undefined

Cookies are set in HTTP Headers. res.cookie() just sets the header for your HTTP result, but doesn't actually send any HTTP. If your code was syntactically correct and it ran, it would actually just sit and not return anything. I also fixed some syntax bugs in your code in this app.get():
app.get('/', function(req, res) {
res.cookie('cart', 'test', {maxAge: 900000, httpOnly: true});
res.send('Check your cookies. One should be in there now');
});

You need to send something out, or at least call res.end(), after setting the cookie. Otherwise all res.cookie() does is add some headers to a list of headers that will be sent out later.

Set cookie name to value, where which may be a string or object converted to JSON. The path option defaults to "/".
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
Here is the Link for more detail
http://expressjs.com/api.html#res.cookie

Related

Application works with app.all but not with app.use... not sure why

I'm having some problems trying to implement some middleware in my app.
Specicially, the app.use() does not seem to catch and I don't understand why.
Below is roughly what I have.
routes/index.js
var Sessions = require('../events');
module.exports = exports = function(app) {
app.use(Sessions.isLoggedIn);
//app.use() does not catch but this does
//app.all('*', Sessions.isLoggedIn);
// Home Page
app.get('/', displayHome);
app.get('/:library/:books', displayLibrary);
}
events.js
module.exports = exports = {
isLoggedIn: function(req, res, next) {
console.log('isLoggedIn');
return next();
}
Any suggestions as to why app.use() is not catching?
UPDATE:
Here is the configuration in ape.js
app.configure(function() {
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.compress()); // compress responses
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(expressValidator);
app.use(express.cookieParser('locket'));
app.use(express.cookieSession({
key: 'locket',
secret: 'mySecret',
cookie: {httpOnly: true, expires: 0, path: '/'}
}));
// cache every file going out
app.use(function(req, res, next) {
if (!res.getHeader('Cache-Control')) {
res.setHeader('Cache-Control', 'public, max-age=' + (86400 / 1000));
}
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
});
routes(app);
The router is responding to the request before your middleware function has a chance to run.
app.js sets up several other middleware functions, then uses app.router. You then call your routes/index.js file, which uses a new middleware function which gets added after app.router.
use your isLoggedIn function before the router, or use it specifically with the routes that need to check login state:
app.get('/', Sessions.isLoggedIn, function(req, res) { ... });

NodeJs req.flash method not available on some requests

I would like to use the req.flash that was removed as of Express 3.0. According the docs, simply configure the app as so to use it:
app.configure(function() {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
});
However, I've configured my app as so:
app.configure('production', function() {
app.use(express.static('/static', express.static(__dirname + '/lib/static')));
app.use(express.errorHandler());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
I've been trying to detect the availability of flash as so:
app.all('/*', function(req, res, next) {
console.log('FLASH: ', req.flash);
....
My logs show the following:
FLASH: undefined
FLASH: undefined
FLASH: function _flash(type, msg) {....
This was displayed with just one request to the '/' route. I understand why there may be multiple requests with the one GET request to '/', however, I'm wondering why req.flash is not available on every request as the docs state.
I think you should change your configuration to:
app.configure('production', function() {
app.use(express.errorHandler());
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('/static', express.static(__dirname + '/lib/static')));
app.use(app.router);
});
I always keep my static route at the end of my middleware.
I think the problem is that your /* route is also firing for /static requests and, since that middleware is declared before the flash() middleware, the request object hasn't yet been modified.

req.cookies in express is not being populated

I am setting a session cookie as part of PassportJS. I can see the connect.sid cookie being passed to the browser, and back to the application on subsequent HTTP requests.
However, when I read req.cookies in one of my routes, it is empty. I have set up express.cookieParser(), express.session(), and passport.session() in configuration settings. Is there anything else that needs to be done in order to use cookies in Express / Node?
Here are my app configuration settings:
app.configure(function () {
app.set("db_url", config.db[app.settings.env]);
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: "keyboard cat"}));
app.use(passport.initialize());
app.use(passport.session());
app.use(users);
app.use(orgs);
app.use(errorHandler);
});
Thanks!
Try req.session instead req.cookies. If you want to store information within the cookie you need to set them similar to
res.cookie('remember', 1, { maxAge: 60 * 1000 });
Then req.cookies should contain
{ remember: '1' }
The default value of req.session is
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
}
}

TypeError: Object #<IncomingMessage> has no method 'flash'

I'm getting the following error while using Node.js and Express. Here are my versions :
Node : v0.8.8
Express: 3.0.0rc3
The following error is obtained while trying to access the page :
TypeError: Object #<IncomingMessage> has no method 'flash'
at routes (/Users/nblavoie/Desktop/HotPie/HotPie/apps/authentication/routes.js:23:8)
I've tried to remove the app.use(app.router); from the app.js with no success. Here is the code that causes the error. See req.flash line.
app.post('/sessions', function(req, res)
{
if(req.body.user == 'piechief'
&& req.body.password == '12345')
{
req.session.currentUser = req.body.user;
req.flash('info', "You're logged in as #{req.session.currentUser}");
res.redirect("/login");
return;
}
else
{
req.flash('error', "Those credentials were incorrect. Try again.");
res.redirect("/login");
return;
}
});
Here is the interesting part of my app.js :
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
secret: "DBBD6BE563419EDB0E5CBD228E603D4AD232CE05434B4FA95C6908B64EA515C3",
store: new RedisStore({
host: "127.0.0.1",
port: "6379",
db: "mydb"
})
}));
app.use(app.router);
app.use(express.static(path.join(__dirname, '/public')));
});
Any idea please? I've took a loof at the Express'flash documentation and I can't see what I'm doing wrong.
req.flash has been removed as of 3.0:
req.flash() (just use sessions: req.session.messages = ['foo'] or similar)
connect-flash can be used as middleware to provide req.flash()
This solved it for me
https://github.com/jaredhanson/passport/issues/61
Now my passport app.configure looks like this:
app.configure(function (){
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
})

Clearing sessions in mongodb, expressjs, nodejs

My configuration:
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: 'MY SECRET',
store: new MongoStore({
db: 'MY SESSION DB',
host: 'localhost',
port:88888
})
}));
app.use(everyauth.middleware());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('dev', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
appPort = config.port; //Setting PORT to 8888 in dev mode.
app.use('/public', express.static(__dirname + '/public'));
});
app.configure('production', function(){
app.use(express.errorHandler());
appPort = config.port;
//Set cache-header-expires to 1 day
var oneDay = 86400000;
//app.use('/public', express.static(__dirname + '/public'));
app.use('/public',express.static(__dirname + '/public', { maxAge: oneDay }));
});
Now, I have a 'logout' link which goes to /logout on my app.
AFAIK, express automatically takes care of clearing sessions on logout. But with my config, I dont think its doing that. For example, A custom variable attached to session
req.session.custom
still holds after logout. However,
req.session.auth
is cleared after logout.
The number of session object in my MongoDb store are only incrementing over time. I am using everyauth as well.
What am I missing or doing wrong?
If you want to fully clear the session for the user on logout you can call req.session.destroy() from your everyauth.everymodule.handleLogout function. Only req.session.auth is cleared when you call req.logout().
why is it creating a new session in mongo store.Is there any way to
prevent it when i am redirected to login again. – loneranger Jun 7 '15 at 5:43
There's a saveUninitialized option to prevent the session to be saved if it does not contain any data.
app.use(session({
secret: 'secret123',
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 60 * 30 // half hour
}),
saveUninitialized: false
}));

Resources