'How to pass flash messages in ejs view

index.js

/**
 * Created by sysadmin on 1/25/2017.
 */

var express = require('express');
var router = express.Router();
var request = require('request');
var session = require('express-session');

var User=require('../models/user');

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var sess;

// get register
router.get('/register', ensureAuthenticated,function(req, res){
    res.render('register');
});

function ensureAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return next();
    } else {
        //req.flash('error_msg', 'You are not logged in');
        res.redirect('/users/login');
    }
}

// Login
router.get('/login', function(req, res){
    res.render('login');
});

router.get('/admin', function(req, res){
    res.render('admin');
});




router.post('/register', function(req, res){
    var username=req.body.username;
    var password=req.body.password;
    var email=req.body.email;
    var role=req.body.role;

    req.checkBody('username','Name is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    req.checkBody('role','role is required').notEmpty();
    var errors=req.validationErrors();

    if(errors){

        res.render('register',{errors:errors})
    }
        else{
            var newUser = new User({
                username:username,
                email:email,
                password:password,
                role:role
            });

            User.createUser(newUser,function(err,user){
                if(err) throw err;
                console.log(user);
            });
            req.flash('success_msg', 'you are registered');

            res.redirect('/users/login');
        }

});

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.getUserbyUsername(username, function(err, user){
        if(err) throw err;
        if(!user){
            return done(null, false, {message: 'unknown user'});
        }
        User.comparePassword(password, user.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch){
                return done(null, user);
            } else {
                return done(null, false, {message: 'Invalid password'});
            }
        });
    });

  }));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.getUserbyId(id, function(err, user) {
    done(err, user);
  });
});

 router.post('/login',
  passport.authenticate('local', {failureRedirect:'/users/login', failureFlash: true}),
  function(req, res) {

      sess = req.session;
//In this we are assigning email to sess.email variable.
//email comes from HTML page.
  sess.email=req.user.role;

    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    console.log(req.user.role);
    if(req.user.role == "admin"){
      req.flash('isAdmin','admin');
//      req.session.role = 'admin';
        res.redirect('/');
    }
    else{
      req.flash('otherusers', 'otherusers'); 
      res.redirect('/');

    }
  });

 router.get('/logout', function(req, res){

    req.logout();
    req.flash('success_msg', 'You are logged out');
    res.redirect('/users/login');
 });


 router.get('/restful', function(req, res){
  sess = req.session;
  console.log(sess.email);

    res.render('restful');
 });

 router.post('/restful', function(req, res){
    var options = {
        uri : 'http://192.168.1.6:8080/RestTGRP/TGRP/checkAPI',
        method : 'post'
    }; 
    var responseFromClient = '';
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            responseFromClient = body;
        }
        else {
            responseFromClient = 'Not Found';
        }
        console.log(responseFromClient);
        //res.json(resss);
        req.flash('response_msg', responseFromClient);

        if(responseFromClient !='Not Found'){
          res.redirect('/users/restful');
        }
        else{
          res.redirect('/users/restful');
        }
    });
 });

module.exports = router;

This is my user.js and I have used here flash messages. Now I want these messages to be displayed in my view. I am using ejs as a view template. How can I pass this values in my view? How to pass this values in the view? I have separate views for register, login. Do I need to declare in each ejs or can we declare in one particular ejs file and include in other ejs pages?



Solution 1:[1]

This node module makes flash messages easy to integrate, tiny and simple to use:

https://www.npmjs.com/package/express-flash

usage: (server)

app.get('/logout', function (req, res) {
    req.flash('logged', null);
    res.render('logout')
  });
  app.post('/logout', function (req, res) {
    req.flash('logged', 'You are logged out');
    res.redirect('/logout');
  });

usage: (ejs view)

<% if(messages.logged) { %>
  <%= messages.logged %>
<% } %>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ericmp