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)?