简体   繁体   中英

Undefined method flash in the view of node.js

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.

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('/');
    });

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') });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM