Eric H.
Eric H.

Reputation: 7014

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.

Upvotes: 0

Views: 1458

Answers (1)

Jim Schubert
Jim Schubert

Reputation: 20357

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.

Upvotes: 2

Related Questions