我正在尝试使用connect-flash显示错误消息,但似乎无效。我已经尝试了几种方法来完成这项工作,但其中任何一项都有效。我需要一个具有类似配置代码的Web应用程序,并且没有任何问题。
这是我的代码:
const express = require('express')
const moment = require('moment')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const db = require('./configs/db')
const flash = require('connect-flash')
const session = require('express-session')
const cookieParser = require('cookie-parser')
const app = express()
app.set('view engine', 'ejs')
app.set('views', 'views')
app.set(db)
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(morgan('dev'))
app.use(cookieParser())
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
app.use(flash());
var sessionFlash = function(req, res, next) {
res.locals.currentUser = req.user;
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
next();
}
app.use(sessionFlash)
app.get('/', function (req, res) {
req.flash('error', 'Welcome');
res.render('test', {
title: 'Home',
})
});
app.get('/addFlash', function (req, res) {
req.flash('error', 'Flash Message Added');
res.redirect('/');
});
我的EJS文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<% if(error){ %>
<div class="">
<h1><%=error%></h1>
</div>
<% } %>
</body>
</html>
答案 0 :(得分:1)