Search code examples
node.jsexpresshttp-redirectflash-messageconnect-flash

req.flash not working with the res.redirect


I am somewhat new to the node and express world so please forgive any of my nobe mistakes, I have a couple of methods that are returning me 500 after I use something like this.

refrence to the error

req.flash('success', 'your password has been successfully changed.');
res.redirect('/user-profile');

also I have tried sending status with it like

res.redirect(302,'/user-profile');

but it also didn't worked out

and when i try to reload the page it works fine (on the second attempt), however if I comment req.flash every things starts to work out just fine, seems like it's causing the issue while it works fine with other methods where I am using it like

req.flash('success', 'You are logged out');
res.redirect('/login');

Code in my index.js file

const express = require('express');
const router = express.Router();
const fs = require('fs');
const bcrypt = require('bcryptjs');
const app = require('../app');
const User = require('../model/user');
const passport = require('passport');
let path = require('path');
router.get('/user-profile', (req,res,next) => {
    res.render('profile',{
        title: 'Profile'
    });
});

router.get('/logout', (req,res,next) => {
    req.logout();
    req.flash('success', 'You are logged out');
    res.redirect('/login');
});

Code in my app.js

// Express Messages Middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
    res.locals.messages = require('express-messages')(req, res);
    next();
});

I have tried to find the solution online, but could not get it working. I am really finding it hard to debug any help would be greatly appreciated.


Solution

  • Solved my error long time ago, in case anyone else is facing the same problem.Here is the answer to it. I had a duplicate of <%- messages() %> in my single ejs file which was causing the issue which eventually was crashing the app.