如何在EJS中使用req.flash()? [英] How do I use req.flash() with EJS?

查看:132
本文介绍了如何在EJS中使用req.flash()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用Express和EJS向客户端发送消息。我看了一遍,但仍然找不到示例或教程。有人能告诉我闪现消息的最简单方法吗?

I want to be able to flash a message to the client with Express and EJS. I've looked all over and I still can't find an example or tutorial. Could someone tell me the easiest way to flash a message?

谢谢!

推荐答案

我知道这是一个老问题,但我最近在尝试自己理解Flash消息和模板时碰到了它,所以我希望这有助于我的情况。考虑到Express 4,express-flash模块和ejs模板的情况,这里有两条路线和一个可以帮助你入门的模板。

I know this is an old question, but I recently ran across it when trying to understand flash messages and templates myself, so I hope this helps others in my situation. Considering the case of Express 4, the express-flash module, and an ejs template, here are 2 routes and a template that should get you started.

First 生成您要显示的Flash消息。这里 app.all()方法映射到 / express-flash 。请求 baseurl / express-flash 使用 req.flash(类型,消息) setter方法创建消息重定向到 baseurl /

First generate the flash message you want to display. Here the app.all() method maps to /express-flash. Request baseurl/express-flash to create a message using the req.flash(type, message) setter method before being redirected to baseurl/.

app.all('/express-flash', req, res ) {
  req.flash('success', 'This is a flash message using the express-flash module.');
  res.redirect(301, '/');
}

下一步将邮件映射到模板中 res.render()目标路线的方法, baseurl / 。这里 req.flash(type) getter方法返回匹配类型的消息, success ,它们被映射到模板变量, expressFlash

Next map the message to the template in the res.render() method of the target route, baseurl/. Here the req.flash(type) getter method returns the message or messages matching the type, success, which are mapped to the template variable, expressFlash.

app.get('/', req, res ) {
  res.render('index', {expressFlash: req.flash('success') });
}

最后,显示<$ c的值$ c> expressFlash ,如果存在,则在 index.ejs

Finally, display the value of expressFlash, if it exists, in index.ejs.

<p> Express-Flash Demo </p>    
<% if ( expressFlash.length > 0 ) { %>
  <p>Message: <%= expressFlash %> </p>
<% } %>

然后启动服务器并访问 baseurl / express-flash 。它应该使用flash消息触发重定向到 baseurl / 。现在刷新 baseurl / 并看到消息消失。

Then start the server and visit baseurl/express-flash. It should trigger a redirect to baseurl/ with the flash message. Now refresh baseurl/ and see the message disappear.

这篇关于如何在EJS中使用req.flash()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆