Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing error message to template through redirect in Express/Node.js

In my Node.js application, I have a function (routed by Express) which presents a form to the user:

app.get('/register', function (req, res) {
  res.render('form');
});

I have another function, routed to the same URL, but which handles POST requests, which receives the data submitted by the previous form. If the form does not validate, it redirects the user back to the form; otherwise, it does what should be done:

app.post('/register', function (req, res) {
  if (validate(req.registerForm)) return res.redirect('back');
  persistStuff(req.registerForm, function (err, data) {
    // Do error verification etc.
    res.redirect('back')
  });
});

What I want to do is to send a error message to be presented, in the line:

if (validate(req.registerForm)) return res.redirect('back');

To write something like

if (validate(req.registerForm)) return res.render('form', {msg:'invalid'});

is unacceptable because I want to follow the POST-REDIRECT-GET pattern. I could do something like

if (validate(req.registerForm)) return res.redirect('/register?msg=invalid');

but it would hardcode an URL in my code and I'd prefer to avoid it. Is there another way to do it?

like image 393
brandizzi Avatar asked Aug 16 '11 13:08

brandizzi


2 Answers

You need to use flash notifications, and it is built into express.

You'll add a message like so: req.flash("error", "Invalid form...");

You'll need a dynamic handler to add the messages to your rendered template, or you can check out the ones TJ has made for express. (express-messages)

like image 74
Dominic Barnes Avatar answered Oct 22 '22 11:10

Dominic Barnes


You could simply have it redirect as res.redirect('..?error=1')

the ? tag tells the browser that it is a set of optional parameters and the .. is just a pathname relative recall (like calling cd .. on terminal to move back one directory) and you're browser will direct to the appropriate page with that tag at the end: http://.....?error=1

then you can simply pull the error on the appropriate page by doing a:

if (req.param("error" == 1)) { // do stuff bassed off that error match };

you can hardcode in several different error values and have it respond appropriately depending on what error occurred

like image 31
gadu Avatar answered Oct 22 '22 12:10

gadu