Undefined method flash in the view of node.js

276 views Asked by At

Problem in accessing flash messages on view in node.js In my Controller

this.req.flash('info','successfully submited');
this.redirect("/home");

In my home view I am not able to get flash messages as

req.flash('info');

EDIT In controller

self.req.flash('message','hello');

In view

<%= req.flash('message) %>

In server.js

app.configure(function (){

  app.use(express.cookieParser());
  app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
  app.use(passport.initialize());
  app.use(locomotive.session());
  app.use(flash());
  app.use(passport.session());
  app.use(app.router);

  app.dynamicHelpers({ messages: require('express-messages') });
});

I have the locomotive framework.

2

There are 2 answers

0
Nikolay Lukyanchuk On

Please see tempdata example https://github.com/MKxDev/TempData

var tempData = require('tempdata');
    var app = express();

    app.configure(function() {
        ...

        // This has to appear BEFORE the router
        app.use(express.cookieParser());
        app.use(express.session({ secret: 'your_super_secret_session_key' })); // please change this!
        app.use(tempData);

        ...
    });

    ...

    // Routes
    app.get('/', function(req, res) {
        // Retrieve tempData value here. It won't exist unless the request
        // was redirected
        var tempVal = JSON.stringify(req.tempData.get('test_val'));

        res.render('index', { title: 'Express', temp: tempVal });
    });

    app.post('/', function(req, res) {
      // Set tempData value here
        req.tempData.set('test_val', { x: 'Hello World!' });

        res.redirect('/');
    });
3
Matthew Bakaitis On

Move your app.use(flash()) higher in the order...see below. Flash needs to be initialized before passport so that flash is recognized and available to passport.

app.configure(function (){
  app.use(express.cookieParser());
  app.use(express.session({ secret:'yoursecret',cookie: { maxAge: 24 * 60 * 60 * 1000 }}));
  app.use(flash()); // moved this up a few lines
  app.use(passport.initialize());
  app.use(locomotive.session());
  app.use(passport.session());
  app.use(app.router);
  app.dynamicHelpers({ messages: require('express-messages') });
});