jaredhanson / connect-flash

Flash message middleware for Connect and Express.
MIT License
1.24k stars 158 forks source link

req.flash return content with brackets ['message'] #42

Closed iwaduarte closed 5 years ago

iwaduarte commented 6 years ago

I'm having a problem with req.flash when I am try to set a flash message inside a function: I am doing:

req.flash('info', 'Yep all good' );

but then when I am using console.log to display it: console.log(req.flash('info'));

I get :[ 'Yep all good' ] with brackets. I do not know what do to fix this. Can someone give me a help. Is that a bug?

kounelios13 commented 6 years ago

I believe this due to req.flash returning an array of strings

sayhicoelho commented 6 years ago

i'm facing with the same issue. cannot get an object from flash() function. any helps?

sayhicoelho commented 6 years ago

without any help, i've made my own script to work with. please see my gist if you are interested https://gist.github.com/sayhicoelho/f3f8009d2d380dc28765c13c65340c0e

iwaduarte commented 6 years ago

I have pretty much abandoned the use of req.flash(). It is buggy and lacks of the documentation to perform this simple task as we can see. I did not get any response either. Instead I highly recommend you to work with res.locals. They do pretty much the same thing if setup properly.

lutzklai commented 6 years ago

This is the expected behavior of req.flash. So if you wanted you could push multiple messages to the same key

req.flash('info', 'message 1');
req.flash('info', 'message 2');

Then in your view you could iterate over the array and display all the messages.


In my use case I knew I would only pass a single error object to flash

req.flash('errors': errorObject);

So now I can fetch it and select the first index

const errors = req.flash('errors');
res.locals.errors = errors.length > 0 ? errors[0] : {};
iwaduarte commented 5 years ago

I have misunderstood this. Thanks!!!

UgbeGodwinIkpe commented 3 years ago

I'm have issues in returning with req.flash() too. I'm trying to return a string message to the view instead it's flashing 1. This is the short code: return res.render('index', { error_msg: req.flash('error_msg', 'Not found'), success_msg: '' })