Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables on res.redirect

Is there an easy way to pass a variable with a res.redirect in node.js / express without having to append it to the URL, or store it in a cookie, or session variable?

Why do I want to do this? Here is an example:

Let's say I have a users page at /users. And I can add users at the page /users/add. I post the form at /users/add, if it has errors it reloads that form with the error messages, if it goes through successfully, it redirects back to the /users page. What I want is the ability to know I just added a user and show a success message for it.

Here is an example of a post:

exports.usersAddPost = function(req, res, next) {
  // validate form

  if (!validated) {
     // go back to form
     return res.render('users/add', req.body.whatever);
  } else {
     // go back to users list
     // need some way to tell users page that a user was just added
    return res.redirect('users');
  }
};
like image 230
codephobia Avatar asked Feb 13 '23 10:02

codephobia


1 Answers

I actually decided to use sessions since I found a nice way to do it fairly elegantly.

Before the redirect I set the session like so:

req.session['success'] = 'User added successfully';
res.redirect('users');

And on the users page I check for a success variable and pass that to my template if it exists, and then to reset it I just set it to null. This works perfectly for what I need.

like image 197
codephobia Avatar answered Feb 15 '23 10:02

codephobia