javascript 如何在 EJS 中使用 req.flash()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11194720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:21:17  来源:igfitidea点击:

How do I use req.flash() with EJS?

javascriptnode.jsexpressejsflash-message

提问by Poison Oak

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?

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

Thanks!

谢谢!

回答by Poison Oak

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.

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

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

首先生成要显示的 flash 消息。这里的app.all()方法映射到/express-flash. 请求在被重定向到 之前baseurl/express-flash使用req.flash(type, message)setter 方法创建消息baseurl/

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

Nextmap 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.

接下来将消息映射到res.render()目标路由的方法中的模板,baseurl/。这里的req.flash(type)getter 方法返回匹配类型 的一条或多条消息success,这些消息被映射到模板变量expressFlash

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

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

最后,在 中显示 的值(expressFlash如果存在)index.ejs

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

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.

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

回答by Florian Margaine

<% if ( message ) { %>
    <div class="flash"><%= message %></div>
<% } %>

Is this what you want? You can use some client-side JS to have it fading out. jQuery example:

这是你想要的吗?您可以使用一些客户端 JS 使其淡出。jQuery 示例:

var message = $( '.message' );
if ( message.length ) {
    setTimeout( function() {
        message.fadeOut( 'slow' );
    }, 5000 );
}

回答by freakish

req.flash()can be used in two ways.

req.flash()可以以两种方式使用。

If you use two arguments

如果你使用两个参数

req.flash(type, message);

where typeis a type of message and messageis actual message (both strings), then it adds messageto the queue of type type. Using it with one argument

wheretype是一种消息类型并且message是实际消息(两个字符串),然后它添加message到 type 的队列中type。用一个参数使用它

req.flash(type);

returns array of all messages of type typeand empties the queue. Additionally this method is attached to the session, so it works per session. In other words, each user has its own set of flash queues. So in your view you can do something like this:

返回所有类型消息的数组type并清空队列。此外,此方法附加到会话中,因此它在每个会话中都有效。换句话说,每个用户都有自己的一组闪存队列。因此,在您看来,您可以执行以下操作:

var messages = req.flash('info');

and then send the messagesvariable to the template and use it there (note that messagesis an array and you can iterate it). Remember that using req.flash('info', 'test');will append a testmessage of type infoonlyfor a current user (associated with the reqobject).

然后将messages变量发送到模板并在那里使用它(注意这messages是一个数组,你可以迭代它)。请记住, usingreq.flash('info', 'test');仅为当前用户(与对象关联)附加test类型为消息的消息。inforeq

Keep in mind that this mechanism is quite weak. For example if a user double clicks on link (two requests send to the server), then he will not see messages, because the first call will empty the queue (of course unless the request generates messages).

请记住,这种机制非常薄弱。例如,如果用户双击链接(两个请求发送到服务器),那么他将看不到消息,因为第一次调用将清空队列(当然,除非请求生成消息)。

回答by VedTopkar

If you use visionmedia's express-messages helper module, it becomes very simple. Github link

如果使用visionmedia 的express-messages helper 模块,就变得很简单了。Github 链接

As it says in the module's docs:

正如模块文档中所说:

Install the module with npm

使用 npm 安装模块

npm install express-messages

You then assign a dynamic helper for messages in the app.config:

然后在 app.config 中为消息分配一个动态助手:

app.dynamicHelpers({ messages: require('express-messages') });

In your EJS file, insert the following where you want your messages

在您的 EJS 文件中,在您想要消息的位置插入以下内容

<%- messages() %>

EJS renders this into:

EJS 将其呈现为:

<div id="messages">
  <ul class="info">
    <li>Email queued</li>
    <li>Email sent</li>
  </ul>
  <ul class="error">
    <li>Email delivery failed</li>
  </ul>
</div>

(of course, you can alter what it renders to in the module's code)

(当然,您可以更改它在模块代码中呈现的内容)

Then, to actually flash a message, include a call to:

然后,要实际显示消息,请调用:

req.flash('info', 'Your message goes here');

回答by Chief Buddy

I was struggling with this as well; Getting my flash message to appear in my .ejs. BUT, I finally got it to WORK and this is what I understand.

我也在为此苦苦挣扎。让我的 flash 消息出现在我的 .ejs 中。但是,我终于让它工作了,这就是我的理解。

Once the getter req.flash('_msgName_');is called it is cleared!

一旦 getterreq.flash('_msgName_');被调用,它就会被清除

Also when you app.use(session());cookie must equal cookie: {maxAge: 720}, essentially a big number.

此外,当您app.use(session());cookie must equal 时cookie: {maxAge: 720},本质上是一个很大的数字。

I was using a console.log() to test the getter, and it was displaying in my console, but not in my .ejs. I took the console.log() out and it worked.

我正在使用 console.log() 来测试 getter,它显示在我的控制台中,但不在我的 .ejs 中。我把 console.log() 拿出来,它工作了。

Here is some of my code.

这是我的一些代码。

Server.js ~

服务器.js ~

app.get('/', function(req, res) {
    // This is where we will retrieve the users from the database and include them in the view page we will be rendering.
    User.find({},function(err, allUsers){
        if(err){
            console.log("Oh no we got an error\n ERROR :: "+err);
        } else {
            // console.log(allUsers);
            res.render('index',{users : allUsers, msg : req.flash('vError')});
        }
    });
});

// Add User Request 
app.post('/users', function(req, res) {
    console.log("REQUESTED DATA:\t", req.body);
    var user = new User(
        {
            name: req.body.name, 
            age: req.body.age
        }
    );
    // Saves user to DB.
    user.save(function(err) {
        if(err) {
            console.log('OOPS, Something went Wrong... \n ERROR :: '+err+'\n');
            for(var key in err.errors){
                // console.log(err.errors[key].message);
                req.flash('vError', err.errors[key].message);
            }
            // **HERE I WAS ACCIDENTALLY CLEARING IT!!!** \
            // console.log(req.flash('vError')); 
            // res.render('index',{users : [], msg : req.flash('vError')});
            res.redirect('/');
        } else { 
          console.log('\tSuccessfully added a new User to the DB!');
          res.redirect('/');
        }
    })
});

index.ejs ~

index.ejs ~

<% if(msg.length > 0) { %> 
    <% for (var error in msg) { %>
        <h3><%= msg[error] %></h3>
    <% } %>
<% } %>