简体   繁体   中英

req.flash() not working after req.session.destroy()

Based on a condition, I need to destroy user's current session, and redirect him to a login page with a message. I use flash to have a show-once-only message. Everywhere, this works fine on my app except here, because here I use req.flash after req.session.destroy() .

How can I achieve this? I have tried placing req.flash() before req.session.destroy() but that does not work, I think because req.session.destroy() clears the session where we just stored the flash message. Thanks.

   if( req.session.adminUser.blocked ){
        req.logout();
        req.session.destroy(()=>{
            req.flash("flashMessage", "You are blocked, Please contact admin");
            req.session.save(function(){
                res.redirect("/admin-panel/login");
                return false;
            });//session.save()
        });
    }

With this code, I get this error - Error: req.flash() requires sessions . If I move the flash statement before the session.destroy statement, then I do not get any error, but the message is not shown.

If you look at flash source you can see that this middleware REQUIRE session to work

req.flash() depends on a valid session, so if you destroy that session, the flash messages are destroyed as well.

It seems to me that it might actually be better to create a separate "blocked" page, and render that, instead of redirecting the blocked used back to the login page (where they can't log in anyway):

req.session.save(function(){
  res.render("/admin-panel/blocked");
});

As a (less-pretty) alternative, you can pass a query string to the login page indicating that the user was blocked:

res.redirect("/admin-panel/login?blocked=true");

And use a check in the login-template to see if it should show a "you are blocked" message.

I realize this is an old post by now, but in case it helps someone.

It looks like using req.logout(); does the trick, this allows req.flash(); to be called afterwards effectively.

"Node version": "14.16.1"
"express": "4.17.2"
"express-session": "1.17.2"
"passport": "0.5.2"
"connect-flash": "0.1.1"
"cookie-parser": "1.4.6"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM