Matěj Zmítko Matěj Zmítko - 5 months ago 50
HTML Question

Flash messages in express and ejs dont show up

I made an authentication app according to one of the tutorials with sqlite3. Everything worked fine until I changed the views from handlebars to html files.

The authentication system works, but I cannot manage to pop up the flash messages. Maybe you could have an advise for me.

My middleware:

var express = require('express');
var path = require('path');
var app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req,res,next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.users = req.user || null;

Server side in this example:'/login',
passport.authenticate('local',{ successRedirect: '/play/gallery',failureRedirect: '/users/login',failureFlash:true }),
function(req,res) {

req.flash('success_msg','You are logged in');



req.flash('success_msg','You succesfully logged out');


and for instance the register.html where I use this:

<%= if (error_msg) { %>

<div class="alert alert-danger"> You are not loged in</div>
<% } %>

Could anybody help me a bit how to declare the code, because this does not even load the registration page.

Thank you in advance.


Solved by myself:

 <% if (error.length > 0){ %>

<div class="alert alert-danger"><%= error %></div>

 <% } %>

<% if (success_msg.length > 0){ %>

 <div class="alert alert-success"><%= success_msg %></div>

 <% } %>
<% if (error_msg.length > 0){ %>

 <div class="alert alert-danger"><%= error_msg %></div>

<% } %>