How to use req.flash () with EJS?

I want to be able to send a message to a client using Express and EJS. I looked through everything and I still cannot find an example or tutorial. Can someone tell me the easiest way to release a message?

Thank!

+5
source share
4 answers

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

-, . app.all() /express-flash. baseurl/express-flash, set req.flash(type, message) 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.

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

expressFlash, , index.ejs.

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

baseurl/express-flash. baseurl/ -. baseurl/ .

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

, ? JS , . jQuery:

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

req.flash() .

req.flash(type, message);

type - , message - ( ), message type.

req.flash(type);

type . , , . , -. , , - :

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

messages ( , messages - , ). , req.flash('info', 'test'); test info ( req).

, . , ( ), , (, ).

+1

visualmedia express-messages, . Github

docs:

npm

npm install express-messages

Then you assign a dynamic helper for messages in app.config:

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

In your EJS file, paste the following where you want to receive messages

<%- messages() %>

AJS does this as follows:

<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 change what it displays in the module code)

Then, to actually start the message, enable the call:

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

All Articles