I am trying to display flash error message in express.js but req.flash('error') return empty array

Inside authControllers.js, I redirect to /signup page along with an error flash message

    const err = validationResult(req);
    //find errors and convert to array
    const reqErrors = err.array();
    const errors = reqErrors.filter(e => e.msg !== 'Invalid value');
    let messages = [];
    //loops through erros and push them into messages array
    errors.forEach((error) => {
        messages.push(error.msg);
    });
    //check if we have error or not
   ** if (messages.length > 0) {
        // Store error into flash , so we display it later
        req.flash('error', messages);
        res.redirect('/signup');
    }else{**
    //move further
    return next();
}
}

Inside userRoutes.js

userRouter.get('/',(req, res)=>{
    console.log("hello from get route")
    console.log(req.flash())
    const errors = req.flash('error')
    console.log(errors.length)
    return res.render('signup',
    {
        title:"Chatting room Log in",
        messages: errors,
        // if error array > 0 then we have an error need to display
        flag :errors.length > 0 
    }
    );
});

When i run the program , this is following console.log(req.flash()) output:

{ error: [ 'Username is required and must be at least 5 characters.', 'Email is invalid', 'Password is required and must be at least 5 characters.' ] }

However, the variable errors is an empty array, thus when I tried to output errors.length. I got 0. It supposed to give me length 3.

Thanks for helping me! I am using connect-flash, passport.js , express.js.

1 answer

  • answered 2019-11-14 06:35 Imran Afzal

    Flash middleware have only single read. As you are reading in console.log() so flash remove all messages after display. So remove your console.log and run it again