【问题标题】:req.flash not showing messagereq.flash 不显示消息
【发布时间】:2022-02-09 06:26:12
【问题描述】:

我在我的 express 项目中使用 Handlebars。我使用 req.flash() 方法,但它不会出现在我的 hbs 文件中。

这是我的代码:

 req.flash('message','Tag already exists');
 res.redirect('/p/tags/add');  

在 .hbs 文件中:

{{#if message}}
<h1>Tag Already ِExists</h1>
{{/if}}

也在我的 app.js 中:

app.use(flash());

似乎是什么问题?

提前致谢!

【问题讨论】:

  • 你能给我们看看 package.json 文件吗

标签: node.js express flash-message


【解决方案1】:

您需要在重定向的 URL 中使用您的 Flash 消息,如下所示:

app.get('/p/tags/add', function(req, res){
  res.render('yourhbsfile', { message: req.flash('message') });
});

编辑:因此,为了澄清关于 flash 消息的混淆,可以在重定向到任何路由之前从任何地方设置它,或者在使用 res.render() 之前在任何中间件内部设置它,并且可以在内部传播该消息reqrequest 对象。您可以打印req 并检查flash 对象以便更好地理解。

【讨论】:

  • 你的意思是res.redirect中没有办法使用?
  • @HamedJavaheri,没有。 Harsh 的意思是你需要在重定向的路由处理程序中执行flash 功能,但不是在它之前。如果您将 flash 作为重定向路由器中的第一件事,那么当应用重定向到路由时,它仍然会在其他任何事情之前执行。
  • 查看 res.redirect API Reference 它不接受除statuspath 之外的任何其他参数。所以我猜你不能用 res.redirect()
  • 那么如何在handleabr端使用now消息呢?
【解决方案2】:

确实,您不能通过重定向添加flash。 你必须在重定向之前执行flash函数,然后你必须在渲染函数中使用它。

boo = (req, res) => {
    req.flash("error", "This is an error!");
    return res.redirect("/index");
}
  • 我正在使用路由,查看 /index 页面时会执行 indexPage 函数。

渲染函数以查看 /index 页面。

indexPage = (req, res) => {
    let message = req.flash();
    res.render("index", {
      message: message,
    });
}

以及如何查看Handlebar中的数据index.hbs

{{#if message.error}} 
    {{{message.error}}} 
{{/if}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2023-03-03
    • 2021-12-12
    • 2011-03-01
    相关资源
    最近更新 更多