Search code examples
node.jspugexpress-4connect-flash

Access flash messages from Jade in Express 4


I am currently learning NodeJS using the Express framework. For some reason, there's not alot of guides for Express 4, but alot for Express 3.

I am trying to pass errors from a "register" function back to the Jade template using connect-flash.

app.js

var express = require('express'),
    session = require('express-session'),
    path = require('path'),
    favicon = require('serve-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    flash = require('connect-flash');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: "testsecret", cookie: { maxAge: 60000 }}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// send errors to page if any.
app.use(function(req, res, next){
    res.locals.success_messages = req.flash('success_messages');
    res.locals.error_messages = req.flash('error_messages');
    next();
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.locals.pretty = true;
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

And in my routes.js, I got this code:

router.post('/register', function(req, res) {
  var params = req.body;
  var email = params.email;
  var username = params.username;
  var password = params.password;
  var error;
  if(!validator.isEmail(email)) {
    error = '<strong>' + email + '</strong> is not a valid email address!';
  }
  if(error.length > 0) {
    req.flash('error', error);
    res.redirect('/');
  }
});

I am 100% sure that there is an error, and that req.flash('error', error); goes through. And I am trying to access this flash message from my index.jade:

.alert.alert-danger #{messages.error}

But for some reason, I am getting error Cannot read property 'error' of undefined. Which ofcourse means that messagesis undefined. However, I've tried with error aswell as error_messages (see app.js, line 38 to 42) with no avail.

Apart from this issue, I wonder if you fellas know of any good resources where I can find express 4 guides?

Thanks!


Solution

  • I see you're using a middleware to access the messages in all the views. It's perfectly fine, but you have to declare it before your routes definition :

    // send errors to page if any.
    app.use(function(req, res, next){
        res.locals.success_messages = req.flash('success_messages');
        res.locals.error_messages = req.flash('error_messages');
        next();
    });
    
    app.use('/', routes);
    

    and change the name of your error to :

    if(error.length > 0) {
        req.flash('error_messages', error);
        res.redirect('/');
    }
    

    Jade will automatically escape your html code, so you'd need to use !{}

    .alert.alert-danger !{error_messages}
    

    If you want this specific error message to not be treated as 'error_messages', you can do it in a simpler manner.

    Jade :

    -if(message)
        .alert.alert-danger !{message}
    

    Server :

    if(error.length > 0) {
        req.flash('error', error);
        res.redirect('/',{message: req.flash('error')});
    }