return to view that fired the form in case of some error! Nojde + Express

0

Good morning, it seems simple but I still can not do it on my own and I did not find it on the net, I just wanted to return to view that triggered the submit, I have a simple register screen. controller - > model in the controller has the validators, in case of error wanted to return to the form already filled! here are the snippets of the codes:

Route:

router.route('/cadastros').post(home.loggedIn, cadastrosController.salvaCadastro);

Controller:

exports.salvaCadastro = (req, res, next) => {

    let contract = new ValidationContract();
    contract.hasMinLen(req.body.nome_cadastros, 3, 'O nome deve conter pelo menos 3 caracteres');
    contract.isRequired(req.body.telefone1_cadastros, 'O telefone é obrigatório');
    contract.hasMinLen(req.body.telefone1_cadastros, 3, 'O telefone deve conter pelo menos 3 caracteres');

    // Se os dados forem inválidos
    if (!contract.isValid()) {
        req.flash('error', contract.errors());
        //req.flash('error', "Erro ao tentar pesquisar.", e);
        res.redirect('/cadastros');
        return;
    }


    modelCadastro.salvarCadastro(req.body)
        .then(idRegistro => {
            req.flash('success', 'Dados salvos com sucesso!');
         //   return false;
            return res.redirect('/cadastros');
        }).catch(e => {
            req.flash('error', "Erro ao tentar salvar os dados.", e);
            res.redirect('/cadastros');
      //      return false;
        });
}

If you need more information please request !!! Thanks in advance!

At +

    
asked by anonymous 19.09.2018 / 15:43

1 answer

0

I got it right now (and on my own, it seems obvious but I got a little heheh), so the question is still there ...

I created a function that returns res.sender ('view' ....); passing the body, the req and the res for it,

From there on the function stays like this ...

module.exports.renderCadastrosView = function (res, req, result, titulo) {

    return res.render('cadastros', {
        dados: result,
        session: req.session,
        idempresa: result.empresa_cadastros,
        titulo: titulo
    });

}

And I call it that:

     if (!form.isValid()) {
         req.flash('error', contract.errors());
         Utils.renderCadastrosView(res, req, req.body,'Editando cadastro');
         return; 
}

per hour is solved !!! At +

    
19.09.2018 / 16:30