我遇到了 connect-flash ,除非我刷新几次,否则所有 Flash 消息都不会加载到页面上,我不知道为什么。
我创建了一个小项目来测试connect-flash,结果是一样的,请检查下面的代码:
App.js 代码:
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
//using flash
app.use(flash());
app.use(function(req, res, next){
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
//flash route
app.get('/flash', (req, res) =>{
req.flash("success", "CONNECT FLASH TEST");
res.render('flash');
});
const port = process.env.PORT || 5000;
app.listen(port, () =>{
console.log(`App has started on port ${port}`);
})
这是 flash.hbs 页面呈现 flash 消息的代码:
<h1>Flash page</h1>
{{#if success}}
<h2>{{success}}</h2>
{{/if}}
非常感谢,任何帮助将不胜感激。