【问题标题】:How to render flash message in Node.JS?如何在 Node.JS 中呈现 flash 消息?
【发布时间】:2021-01-06 17:07:41
【问题描述】:

我试图在不渲染的情况下显示 Flash 消息,只需重定向。怎么可能?

const session = require('express-session');
const bodyParser = require('body-parser')
const urlencoded = bodyParser.urlencoded({extended:false})
const cookieParser = require('cookie-parser');

const flash = require('connect-flash');
app.use(cookieParser('secret'));
app.use(session({
  secret: 'keyboardSecrIncKey',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true, maxAge: 60000 }
}))

app.use(flash());

app.use('/test',urlencoded,(req,res,next)=>{
  if(req.body.name == ''){
    req.flash('info', 'Please Enter Your Name.');
    res.locals.message = req.flash();
    console.log(res.locals)
    res.redirect('back')
  }
  else{
    next()
  }
});

我正在使用车把视图引擎。这是我的 test.handlebars 文件:

{{#if messages}}
 It is working
{{/if}}

但它不会显示任何文本。如果我使用 res.render('test', {...}) 它正在工作。但是当我点击刷新按钮时,浏览器会向我发送警报(确认重新提交等)

【问题讨论】:

  • 您了解req.flash() 的工作原理吗?无论您闪烁什么,都必须通过您的代码呈现为未来的响应。因此,如果您重定向到没有任何代码来显示来自.flash() 的任何内容的页面,则不会显示任何内容。
  • 谢谢。明白了

标签: javascript node.js express handlebars.js message


【解决方案1】:

当您重定向时,您告诉用户的浏览器显示其他页面。您将在该页面中显示您的 Flash 消息,而不是在使用 req.flash() 创建 Flash 消息的页面中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多