简体   繁体   中英

req.flash() node express 4

I like use req.flash(), but didnt work. I tried different ways. Result was nothing. #{message} is empty. I dont know why... thanks to the help!

server.js:

var express = require('express');
var flash = require('connect-flash');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session')

var app = express();

app.use(cookieParser('secret'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

controller:

app.get('/feedback', function (req, res) {
    res.render('feedback', { message: req.flash('info')
    });
});

app.post('/fb', function(req, res) {
    req.flash('info', 'hello world');
    res.redirect('/feedback');
});

view.jade:

           p #{message}

Render your view again with the flash as your message object.

app.post('/fb', function(req, res) {
   res.render('feedback', { 
      message: req.flash('hello world')
   });
});

Displaying error message we can use connect-flash node module

configuring flash module

var flash = require('connect-flash');

app.use(flash()); connect-flash module expose the req.flash() method that allow you create and retrieve the flash message

example

app.get('/flash', function(req, res){
  // Set a flash message by passing the key, followed by the value, to req.flash(). 
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

app.get('/', function(req, res){
  // Get an array of flash messages by passing the key to req.flash() 
  res.render('index', { messages: req.flash('info') });
});

follow this link https://www.npmjs.com/package/connect-flash

inside jade you can access

local.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