codephobia
codephobia

Reputation: 1590

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');
  }
};

Upvotes: 4

Views: 14570

Answers (3)

codephobia
codephobia

Reputation: 1590

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.

Upvotes: 9

mscdex
mscdex

Reputation: 106696

What about just displaying simple html with a meta refresh? Example:

function redirectFlash(url, timeout, msg) {
  var defaultTimeout = 5;
  if (typeof timeout === 'string') {
    msg = timeout;
    timeout = defaultTimeout;
  } else if (timeout === undefined) {
    msg = '';
    timeout = defaultTimeout;
  }
  return '<html><head><title>Redirecting ...</title><meta http-equiv="refresh" content="'
         + timeout
         + ';url='
         + url
         + '"></head><body>'
         + msg
         + '<br /><a href="'
         + url
         + '">Click here to return manually</a></body></html>';
}

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.end(redirectFlash('/users', 'User added successfully. Returning you to the user list ...'));
  }
};

Upvotes: 0

Jaime Gomez
Jaime Gomez

Reputation: 7067

If you can use javascript, you could use the http referer and assume a user was just added, since according to your workflow that's the only way it could happen:

document.referrer == "/users/add"

Upvotes: 0

Related Questions