提问者:小点点

如何保存flash消息和重新加载页面后重置?


我正在使用connect-flash来提醒登录页面中的一些错误/警告/成功消息。 我要解决的问题是:

  1. 当数据库中不存在用户名时,显示错误消息。
  2. 重新加载页面后删除错误

这就是我如何配置app.js:

const express = require('express');
const app = express(); 
const session = require('express-session');
const bodyParser = require('body-parser');
const flash = require('connect-flash');

const TWO_HOURS = 1000 * 60 * 60 * 2 //T = 2 HOURS COUNTER

const {
    NODE_ENV = 'development',
    SESSION_LIFETIME = TWO_HOURS,
    SESSION_NAME = 'session-ID',
    SESSION_SECRET = 'session-Key'
} = process.env;
const IN_PROD = NODE_ENV === 'production'; //IF Node env. is production set in_prod to true

app.use(bodyParser.urlencoded({extended: true})); //Use body parser to express
app.use(bodyParser.json()); //enable reading JSON files

app.set('view engine', 'ejs'); //Allow app to use EJS files

//USE SESSION with required variables
app.use(session({
  name: SESSION_NAME,           //Name of the session
  resave: false,                //Forces the session to be saved back to the session store - NOT ENABLED
  saveUninitialized: false,     //Forces a session that is 'uninitialized' to be saved to the store - NOT ENABLED
  secret: SESSION_SECRET,       //This is a secret key used to sign the session id cookie
  cookie: {
      maxAge: SESSION_LIFETIME, //When the session will expire 
      sameSite: true,           //'strict'
      secure: IN_PROD           //Only for https channel enabled
      //domain: --(default)-- current domain
  }
}));
app.use(flash()); //USE FLASH MESSAGES

const usersRouter = require('./routes/users.js'); //Import and Use : Users Router
app.use(usersRouter);

app.get('/', (req, res) => {
    const {userId} = req.session; //Set new object called userId in object req.session
    //const alertMessage = req.session;
    return res.redirect('/user_login');
});

users.js:

router.get('/user_login', redirectHome, (req, res) => {     

    //console.log("LENGTH = " + req.flash("message").length);
    //res.render('userEntries/login', {messages: req.flash('errorMessage')});

    console.log("LENGTH = " + res.locals.msg);
    res.render('userEntries/login', {messages: res.locals.msg});
});

router.post('/user_login', redirectHome, (req, res) => {

    //... declaring variables (username, password) and sqlString

    getConnection().query(sqlString, [username, 1], async (err, results, fields) => {
        
        //Catch error with MySQL connection
        if(err){
            console.log("    > The connection with the DB have failed:\n" + err + "\n");            
            return res.sendStatus(500);      
        }

        //USERNAME DOES NOT EXISTS
        if(!results.length) {
            console.log("    > Cannot fetch user from the database\n");
            
            //req.flash("type", "danger");
            //req.flash("intro", "ERROR!");
            req.flash('errorMessage', 'Cannot find username, please try again');
            res.locals.msg = req.flash("errorMessage");
            console.log("#LENGTH = " + res.locals.msg);

            return res.redirect('/user_login');
        }
        //.... more if statements below
    });
});

EJS:

<% if(locals.msg) { %>
    <div class="alert alert-success" style="text-align: center;">
        <% locals.msg %>
    </div>
<% }%>

使用上面的代码,将导致以下未定义的场景。 我在这里执行的事件是

  1. 转到“/”根
  2. 输入无效的用户名和密码
  3. 提交表单

控制台:

::1 - GET / HTTP/1.1 302 66 - 7.120 ms
LENGTH = undefined
::1 - GET /user_login HTTP/1.1 304 - - 2.328 ms

    > Cannot fetch user from the database

#LENGTH = Cannot find username, please try again
::1 - POST /user_login HTTP/1.1 302 66 - 22.432 ms
LENGTH = undefined
::1 - GET /user_login HTTP/1.1 200 5022 - 3.715 ms

有什么特别的原因为什么这不起作用吗? 是否与我的会话配置有关? 我还尝试过在呈现页面时使用req.flash(“errormessage”),但也没有工作! 我也尝试过将EJS if语句设置为如下所示(见下图),但也不起作用。

<% if(message.length > 0) { %>
    <div class="alert alert-success" style="text-align: center;">
        <%= message %>
    </div>
<% } %>

更新:

<% if(alertMessage.length > 0) { %>
    <div class="alert alert-danger" style="text-align: center;">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <strong>ERROR!</strong> <%= alertMessage %>
    </div>
<% } %>
router.get('/user_login', redirectHome, (req, res) => {     
    res.locals.msg = req.flash("message");
    res.render('userEntries/login', {alertMessage: res.locals.msg});
});


//POST REQUEST :
//USER DOES NOT EXISTS
if(!results.length) {
    console.log("    > Cannot fetch user from the database");
    req.flash("message", "The username or password are invalid, please try again!");
    return res.redirect('/user_login');
}

共1个答案

匿名用户

更新:查看您正在设置post请求中的消息:res.locals.msg=req.flash(“errormessage”);

但在下一行,您也读到了:

res.locals.msg = req.flash("errorMessage");

删除最后一行,因为从flash读取也会从flash中删除消息。 您不需要设置为本地,因为您将重定向。

为当前请求生成响应局部变量。 因此,如果您将locals设置在post上,那么它在其他get请求上是不可用的。 这是另一个要求,那些当地人都是新来的。

在get请求中:

res.locals.msg = req.flash('errorMessage');

Flash存储该值,您需要将其传递给本地用户。