Being new to node js and express has me wondering the best ways to get things done. Are there any specific conventions used in working with forms?
I use express-validator to validate input fields.
Here's an example:
app.post('/login', routes.login.post);
//routes/login.js
exports.login.post = function(req, res){
req.assert('username', 'Enter username').notEmpty();
req.assert('password', 'Enter password').notEmpty();
res.locals.err = req.validationErrors(true);
if ( res.locals.err ) {
if ( req.xhr ) {
res.send(401, { err: res.locals.err });
} else {
res.render('login');
}
return;
}
//authenticate and set user in session here
};
I strongly recommend you to pass all of your forms' data via any kind of XSS attacks or other injections filter. For example, you may use node-validator
It's rather simple to use. To filter XSS injections, just write:
req.sanitize('textarea').xss();
etc. More docs can be found here: node-validator