1

I read somewhere that it's conventional to re-render a page to show error messages and re-direct to show success messages. I'm using this principle in some of my code in express js and it's leading to a few headaches.

For example, imagine a user inputs invalid information into a form. I would handle it by doing something like this:

app.post('/lists', (req, res) => {
  let title = req.body.todoListTitle.trim();
  if (!title) {
    req.flash("error", "Please provide a title");
    res.render("new-list", {
      flash: req.flash(), 
    });
});

This is a bit annoying because I have to pass a "flash" object into my view every time there's an error in order to re-render the page with the error.

However, when I display a "success" message it's a lot easier. Because the convention is to re-direct (which issues another "get" request) I can just add custom middleware at the top of my file that handles errors.

app.use((req, res, next) => {
  res.locals.flash = flash();
  delete req.session.flash 
  next();
})

And by doing this, I can keep the middleware that actually handles the request pretty simple. Despite not passing the errors to my view, they will be automatically passed in because of my custom middleware above.

app.get('/lists', (req, res) => {
  res.render('lists');
});

So my overall question is the following: why does this convention exist? Wouldn't it be simpler to always just re-direct when we want to display messages (regardless of whether they are success messages or failure messages)?

bugsyb
  • 5,662
  • 7
  • 31
  • 47

1 Answers1

0

i may be wrong, but to me, this situation is only related to forms.

when you are filling a form you dont want to retype everything when there is a failure. therefore if there is a failure you want :

  • to be able to do f5 to retry (doable only if not redirected : i guess that only programmers know and like this behavior)
  • to see the error on the page, and click "send" again (can be done using rerender or with redirect, as long as the form is still filled)

ps: If the form is pushed using ajax there is no redirect/rerender problem. consider it :)

Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18