我connect-flash
用来在我的登录页面中提醒一些错误/警告/成功消息。我要解决的问题是:
- 当数据库中不存在用户名时显示错误消息。
- 重新加载页面后删除错误
这就是我配置的方式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');
});
用户.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 - 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">×</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');
}