2
votes

I am trying to validate the values in the controller and send the flash error message to the EJS view file in Sailsjs Framework.

I am getting the following error message:


 if(flash && flash.err) { 
>>   flash is not defined in ejs file.

I have added the flash policy in config/policies.js

 '*': 'flash', 

And this is how I am redirecting to the error view..

var usernamePasswordRequiredError = [{
                      name: 'usernamePasswordRequired',
                      message: 'You must enter both a username and password.'
                    }]

                    req.session.flash = {
                      err: usernamePasswordRequiredError
                    }

                   res.redirect("/user/loginpage");
                   return; 

Flash.js content


 Policy File:
    module.exports = function(req, res, next) {
    res.locals.flash = {};
    if(!req.session.flash) return next();
    res.locals.flash = _.clone(req.session.flash);
    req.session.flash = {};
    next();
};

Help me to resolve this Flash is not defined error in view files.

3
Here's a screencast on implementing a flash message in sails irlnathan.github.io/sailscasts/blog/2013/08/27/… - JohnGalt

3 Answers

3
votes

Sails.js has connect-flash baked-in, so I'm using this:

On the server, to set:

req.flash('info', 'OHai');

On the client, to get:

res.req.flash('info');

This means I don't have to mess around with _.clone() or that big gist, and if you do multiple req.flash('info', '...'); calls, you get an array of all the values when you retrieve it on the client-side. Of course, you can use whatever label (not just 'info') you want too.

Let me know if you need more detail.

1
votes

With the flash policy suggested in irlnathan's screencast, the res.locals.flash object should be defined, at least equal to {}, hence Express should not throw the error you got.

But policies apply only to controllers, not to mere views.

Did you make sure sails serves the ejs view from a controller, not from the main config/routes.js configuration file?

0
votes

Your code looks pretty close to a gist I saw and I like this approach a bit more than yours. It's kind of the same in spirit but the setting of the flash error and notice messages occur in the policy.

https://gist.github.com/BenBarber/5700061