【发布时间】:2019-08-16 03:14:15
【问题描述】:
我正在 Node 中创建一个简单的 CRUD,Express 使用 PUG 作为模板引擎。每当操作完成或失败时,我都会在 .js 文件中使用 req.flash("name","message"),然后使用 res.redirect 到特定页面。
但是重定向后,我看不到要在警报中显示的消息。
最初,我对这个问题有同样的问题:Connect flash not displaying messages in Pug
但是在我将代码修改为解决方案后,我仍然没有收到任何消息。
这是我的 Index.js 代码:
...
const flash = require('connect-flash');
...
...
...
app.use(flash());
app.use((req, res, next) => {
res.locals.errs = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
...
...
...
这是我的 req 代码,在 POST 方法中使用 res 将文档保存到 MongoDB 中的集合:
Category.findOne({title: req.body.title}, (err, doc)=>{
if(doc){
res.render('admin/add_category', {
errors: [{msg: 'Category already exists.'}],
category: req.body.title
});
}
else{
var cat = new Category({
title: req.body.title,
slug: req.body.title.replace(/\s+/g, '-').toLowerCase()
})
cat.save((err)=>{
if (err) return console.log(err);
req.flash('info', 'category added'); //doesn't work
res.redirect('/categories');
})
}
这是我的哈巴狗来展示闪光灯。
if infos
for info in infos
div.alert.alert-info #{ info }
if errs
for error, i in errs
div.alert.alert-danger #{ error }
这个用于显示 flash 消息的 pug 文件名为 nav.pug,它包含在使用 include ../includes/nav.pug 的主页中
我只是想确保消息在重定向后显示在页面上。但事实并非如此。
【问题讨论】: