【问题标题】:Why Pug isn't showing any message when I do res.redirect after req.flash?当我在 req.flash 之后执行 res.redirect 时,为什么 Pug 没有显示任何消息?
【发布时间】: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 的主页中

我只是想确保消息在重定向后显示在页面上。但事实并非如此。

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

    阅读 Nick Gagne 的回答后,我试图了解会话。 事实证明我需要更改我的快速会话中间件设置。因为cookies: { secure: true}网站需要在https中运行,但不幸的是我在localhost上运行服务器,这意味着当我更改为cookies { secure: false }时会显示flash消息。
    最终代码:

    app.use(session({
      secret: 'secret',
      resave: false,
      saveUninitialized: true,
      cookie: {secure: false }
    }));
    

    【讨论】:

      【解决方案2】:

      看您的代码并不清楚,但您是否按照connect-flash GitHub page 的建议使用cookieParser 和会话中间件?

      var flash = require('connect-flash');
      var app = express();
      
      app.configure(function() {
        app.use(express.cookieParser('keyboard cat'));
        app.use(express.session({ cookie: { maxAge: 60000 }}));
        app.use(flash());
      });
      

      问题在于 Express 默认是无状态的,所以当你指示浏览器重定向时,它会向 /categories 发送一个新请求,但 Express 无法知道这个请求是同一个“会话”的一部分",因此无法加载 Flash 消息。

      【讨论】:

      • 我不使用 cookieParser 和会话中间件,但是当我尝试您的代码时,它说“app.configure 不是函数”。我有一个问题,你传递给cookieParser()函数的参数有什么用?编辑:您的示例与我的代码无关,它是 Express 3 代码。我正在使用 Express 4
      • 我使用express-session 模块但不是cookieParser。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 2021-11-09
      • 2022-11-04
      • 1970-01-01
      • 2016-12-03
      • 2019-11-20
      相关资源
      最近更新 更多