1

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.

Sean Liu
  • 831
  • 1
  • 11
  • 23
  • 1
    Comment out `console.log(req.flash())` and see if error variable now has value or not. – Mat J Nov 14 '19 at 05:39
  • wow, it actually works!. Thanks for your answer. Would you mind expand more why my previouse code doesnt work? – Sean Liu Nov 14 '19 at 05:44
  • 1
    I'm seeing this library for first time, but from the look of it, I think its only single read. So, first time you read the message, it is also deleted from session. Otherwise, those message will stay there and stale messages will be displayed right? – Mat J Nov 14 '19 at 05:50

1 Answers1

4

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

Imran Afzal
  • 134
  • 1
  • 9