I am using node.js and express to make a CRUD web app, and I am trying to work out how to get a flash message to appear on a data entry form when server side validation fails. I am using express-flash for the flash messages.
The validation code works, returning errors, and I create the flash message:
var errors = validateForm(req);
if(errors){
req.flash('info',errors);
res.render('edit', {messages: req.flash('info')});
}
And display the message in the edit.jade file:
if messages.info
p #{messages.info}
The problem is that I am editing a specific object, and the url is not /edit, but /edit/objectID. The get for the page is like this:
router.get('/edit/:id', function(req, res) {
var db = req.db;
var collection = db.get('mydb');
collection.find({ID: req.params.id},{},function(e,docs){
res.render('edit', {"object" : docs});
});
});
Is it possible to add a flash message for server side validation after a POST has been sent without losing the page ID? I don't need all the data from the edit, there will be client side validation to hopefully pick up any errors, but I would like server side validation errors to cause the user to land on the same object page as they left.
You can declare your post route as:
router.post('/edit/:id', function(req, res) {
// logic to check for errors
// if errors, set flash message and
// redirect to /edit/:id
});
Then on, you can use the ID in the post route to redirect to the edit page of the same resource that the user posted the form for. You will also be able to access the flash error messages in the template.
* Edit * In order to use flash on redirect you would need to add it the middleware.
app.configure(function() {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
});