andrescabana86
andrescabana86

Reputation: 1788

Sending an error message to the users in router with nodejs

The users on my website can change their passwords.

The problem is that when the server produces an error in the process I have to set a warning message and say something like this:

'Warning, the password couldn't be changed, please try again!'

I made two routes in express

app.get('/editMode/:user',ensureAuthUser,routes.user.editMode);
app.get('/editMode/:user/:message',ensureAuthUser,routes.user.editMode);

The first shows the editMode template
The second is supposed to show the editMode and a message from the server

In the editMode.js

var warn=null;
    if(req.params.message) warn=validWarn(req.params.warn) ?JSON.parse(req.params.message) :null;
    console.log('message value: '+req.params.message);
    console.log('warn value: '+warn);

In both cases when I redirect to /editMode/+'[email protected]'+/+'warning message' or /editMode/+'[email protected]' I get

console.log(req.params.message)// value: undefined
console.log(warn)// value: null

Why can't I send a message to the user if my db can't change the password?

EDIT 2

editMode render

return res.render('templates/edit_template,
                            {
                                title: title,
                                usuario: req.session.passport.user,
                                warning: warn || null,
                            })

in the template edit_template.jade

-if(warning && warning.length)
                    h2 Error: #{warning}
                -else
                    h2 success

Upvotes: 0

Views: 164

Answers (1)

robertklep
robertklep

Reputation: 203241

Since you're using sessions, I would store the warning in the session:

if (theErrorOccurred)
{
  req.session.warning = 'this is your warning message';
}
else
{
  req.session.warning = null;
};
res.redirect('/editMode/...');

And pass it to your template in routes.user.editMode:

return res.render('templates/edit_template', {
  title   : title,
  usuario : req.session.passport.user,
  warning : req.session.warning
});

Also check out connect-flash as a more elaborate way of passing around different types of messages between requests.

Upvotes: 1

Related Questions