简体   繁体   English

express-validator 从 controller 调用方法的问题

[英]Problem with express-validator calling a method from controller

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.我正在尝试使用 express-validator 验证用户数据,但是当我从路由文件中调用 controller 中的用户注册方法时,页面不会加载。 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:这是我的 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: 1.我想你可以在你的 controller 中检查你的验证错误,你将你的 function 直接传递给你的路由,这是你的路由文件:

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:这是你的 controller function:

import Hash from '../lib/bcrypt';从 '../lib/bcrypt' 导入 Hash; import pool from '../database/db';从 '../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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM