0

I'm running into some weird issues with connect-flash, I've used it in other projects in the exact same manner and it worked fine, here is what I have:

Some Route

if (err) {
    req.flash('message', [{
      class: 'alert-danger',
      message: 'TEST'
    }]);

    res.redirect('/error');
}

error route

router.get('/error', function (req, res, next) {
  console.log('---in error route')
  console.log(req.flash('message'));

 res.render('error', {
    message: req.flash('message'),
    layout: layout
  });
})

console.log

---in error route
[ { class: 'alert-danger', message: 'TEST' } ]

error.hbs

{{#if message}} 
    {{#each message}}
        <div class="{{this.class}}">{{this.message}}</div>
    {{/each}} 
{{/if}}

Clearly it's in there, but there is no printout, if I copy the exact smae thing from the first route to error, it displays (which won't work for me, but just for testing to make sure the hbs template logic works):

router.get('/error', function (req, res, next) {

  req.flash('message', [{
    class: 'alert-danger',
    message: 'TEST'
  }]);
  res.render('error', {
    message: req.flash('message'),
    layout: layout
  });
})

It's probably something simple, but I have no idea what it is.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86

3 Answers3

8

Ok after some experimentation and by pure accident, I found out that The console.log apparently clears the flash!!!!

I hope this helps anyone who runs into this issue.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86
4

I know you already found a solution, but for anybody with the same issue, what the problem actually is is that when you use req.flash() to retrieve the flash messages, it actually deletes that message after retrieving it.

Had you done this:

console.log(req.flash('message'));
console.log(req.flash('message'));

You would have received something similar to this output:

[ 'TEST' ] 
[]

This is because the first call to req.flash('message') retrieves and deletes the given message.

Additionally, had you done this:

req.flash('message');
console.log(req.flash('message'));
console.log(req.flash('message'));

You would have received output that was similar to this:

[]
[]
Fearnbuster
  • 806
  • 2
  • 14
  • 19
0

Check the version of express you are using. I was having the same issue as I was using express 4.x.x with connect-flash. Connect-flash works with express 3.x.x and Connect-flash-plus works with express 4.x.x.

Pavan
  • 35
  • 6