I'm trying to validate user data using express-validator, but when I call the user registration method in the controller from routes file, the page doesn´t load. If I extract the method to the route, it works. I want to keep it separated to keep some order in my project. Here is my routes file:
import { Router } from "express";
import RegisterController from '../controllers/RegisterController';
import { body, validationResult } from "express-validator";
import pool from '../database/db';
import Hash from '../lib/bcrypt';
const router = Router();
router.get('/', (req, res) => {
res.render('home', {
title: 'Inicio',
});
});
router.get('/formulario-registro', RegisterController.index);
router.post('/register', [
body('username')
.notEmpty()
.withMessage('El nombre de usuario no debe quedar vacío.'),
body('email')
.notEmpty()
.withMessage('El email no debe quedar vacío')
.isEmail()
.withMessage('El email debe de tener un formato correcto.'),
body('password')
.notEmpty()
.withMessage('La contraseña no debe de quedar vacía.')
.isLength({
min: 8
})
.withMessage('La contraseña debe de tener 8 caracteres como mínimo.')
.custom((value, { req }) => {
if (value !== req.body.confirm__password) {
return false;
} else {
return true;
}
})
.withMessage('Las contraseñas deben coincidir.')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
} else {
RegisterController.register;
}
});
router
.get('/formulario-login', (req, res) => {
res.render('login_form', {
title: 'Inicio de sesión'
});
});
export default router;
Here is my controller:
import Hash from '../lib/bcrypt';
import pool from '../database/db';
class RegisterController {
index(req, res) {
res.render('register_form', {
title: 'Registro'
});
}
register(req, res) {
const sql = 'INSERT INTO contact_app.users (username, email, password) VALUES (?, ?, ?)';
pool.query(sql, [req.body.username, req.body.email, Hash.encryptPass(req.body.password)], (err) => {
if (err) {
console.error(err);
} else {
console.log('User registered correctly.');
}
});
res.redirect('/formulario-login');
}
}
export default new RegisterController;
Thanks in advance!
1. I think you can check your validation error in your controller and you pass your function directly to your route, this is your route file:
router.post('/register', [
body('username')
.notEmpty()
.withMessage('El nombre de usuario no debe quedar vacío.'),
body('email')
.notEmpty()
.withMessage('El email no debe quedar vacío')
.isEmail()
.withMessage('El email debe de tener un formato correcto.'),
body('password')
.notEmpty()
.withMessage('La contraseña no debe de quedar vacía.')
.isLength({
min: 8
})
.withMessage('La contraseña debe de tener 8 caracteres como mínimo.')
.custom((value, { req }) => {
if (value !== req.body.confirm__password) {
return false;
} else {
return true;
}
})
.withMessage('Las contraseñas deben coincidir.')
], RegisterController.register);
and this is your controller function:
import Hash from '../lib/bcrypt'; import pool from '../database/db';
class RegisterController {
index(req, res) {
res.render('register_form', {
title: 'Registro'
});
}
register(req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
const sql = 'INSERT INTO contact_app.users (username, email, password) VALUES (?, ?, ?)';
pool.query(sql, [req.body.username, req.body.email, Hash.encryptPass(req.body.password)], (err) => {
if (err) {
console.error(err);
} else {
console.log('User registered correctly.');
}
});
res.redirect('/formulario-login');
}
}
export default new RegisterController;