node.js - 如何在 express 4.x 中使用 connect-flash 和 ejs

标签 node.js ejs connect-flash

我有一个项目需要使用connect-flash ,我正在使用 View 引擎作为 ejs。即使我配置一切都很好,在我看来,connect-flash 也不起作用。有人可以帮我估计一下吗?

这里我是如何定义 session 、connect-flash 和全局变量的:

app.use(cookieParser());
//Express session middleware
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));

//Connect flash middleware
app.use(flash());

//Global varibales
app.use(function (req, res, next) {
    res.locals.error = req.flash('error');
    res.locals.success = req.flash('success');
    next();
});

导出模块get函数如下:

module.exports.xxx_index_get = function(req, res) {
xxx.findOne({
    id: 'xxx'
}).then(xxx=> {
    req.flash('success', 'user succesfulyl registered')
    res.render('xxx/xxx', {
        xxx
    });
});};

这是 ejs 文件:

<% if(success.length > 0) { %><div class="alert alert-success">
<%= success %>    </div><% } %>

如果有人能提供帮助,我将不胜感激。我错过了什么吗?

最佳答案

我假设您已经了解了 Flash 的所有基本细节。

在你的路由中包含下面的代码

module.exports.xxx_index_get = function(req, res) {
xxx.findOne({
    id: 'xxx'
}).then(xxx=> {
    req.flash('success', 'user succesfulyl registered')
res.locals.message = req.flash();
    res.render('xxx/xxx', {
        xxx
    });
});};

然后在你的 View 中尝试使用这样的东西

<% if(locals.message){ %>
    <div class="alert alert-success" role="alert">
        <strong>Well done!</strong> <%=message.success%>
    </div>
    <% } %>

希望对你有帮助。

关于node.js - 如何在 express 4.x 中使用 connect-flash 和 ejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906557/

相关文章:

javascript - req.flash 不是函数 - 初始化顺序

node.js - 如何将 Electron 应用程序和 Flask 服务器打包成一个可执行文件

javascript - Socket.IO 将数据发送到我自己的房间

javascript - 无法导入模块 : You may need an appropriate loader

javascript - 如何根据它是 Node.JS 中的 $regex 还是 $text 对 Mongoose 结果进行排序?

node.js - MongoDB - 获取排行榜前 5 个字段

node.js - 使用node的ejs模板框架处理php文件

node.js - 使用 Connect-flash 和 Jade 的警报消息

mysql - 比较 "for"循环内的数据

node.js - flash、connect-flash 和 express-flash 之间的区别