Node.js server error (ejs)

Asked

Viewed 164 times

1

hello

I have that code:

router.post('/loginCli', function(req, res, next) {
  var j;
  conn.query('SELECT * FROM bdlabella.tbclientes order by email_cli', (err, results) => {


    if(err){
      console.log(err);
    }
    // valida se o email ja existe no banco.
    var dados = results;
    dados.forEach(function(row){
      if(row.email_cli == req.body.email_cli){
        loginCli.render(req, res, "Usuario ja cadastrado com esse email!");
      } else if(req.body.senha_cli != req.body.Csenha_cli){//valida se as senha == confirmar senha
        loginCli.render(req, res, "Senha nao compativel");
      } else {
        loginCli.save(req.body).then(results =>{
          loginCli.render(req, res, null, "Cadastro realizado com sucesso!");
          break;
        }).catch(err=>{          
          loginCli.render(req, res, err);
        });
      }

    });


  });

});

And he’s making that mistake when it comes to saving in the bank

POST /loginCli 200 150.578 ms - 4375
GET /css/bootstrap.css 304 1.845 ms - -
GET /css/estilo.css 304 6.180 ms - -
GET /engine0/style.css 304 0.842 ms - -
GET /js/main.js 304 1.798 ms - -
GET /engine0/jquery.js 304 2.988 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  labelle:server Listening on port 3000 +0ms

C:\E. S\laBelle\routes\index.js:68
          break;
          ^^^^^

SyntaxError: Illegal break statement
    at process.nextTick (C:\E. S\laBelle\node_modules\mysql2\lib\commands\query.js:72:16)
    at processTicksAndRejections (internal/process/task_queues.js:79:9)
[nodemon] app crashed - waiting for file changes before starting...

Talking about you can’t use the break, only that if I don’t use it and will save in the bank the number of times referring to the records that already have there for example has 2 records, it goes there and saves the same thing 2 times.

  • 1

    What’s the idea of having break; in the code? What do you want that break; do?

2 answers

1


You haven’t made your goal with your code very clear, looking at it it seems to me that you want to check whether the email already registered in Database(DB) and if you are not registering.

But your problem doesn’t seem to be the break and yes the idea and implementation that you are making of that goal.

This seems to be your initial idea, looking at your code:

  1. Make a query in your DB that returns all records.
  2. With this data make a forEach to check if the email is registered.

    • If the email nay is registered, cadastra.
    • If the email this registered, unregistered.


The problem with your idea/implementation

In the foreach each time you check a record that is not a registered email it will register the email.
Apparently you noticed that and thought that a break would resolve, however if the first email returned by your query is not the email informed it will register.

In short: Taking all DB records to check 1 by 1 is an unnecessary processing expense and running the register within the forEach will generate a lot of problems.

I need to do a one-by-one check using forEach

Now let’s say you need to check 1 to 1, for some reason, the best way to make it work is to pull the user creation out of the forEach, use the forEach just to see if he meets any user, if not finding cadastra, getting +/- like this:

router.post('/loginCli', function(req, res, next) {
var j;
conn.query('SELECT * FROM bdlabella.tbclientes order by email_cli', (err, results) => {

    if(err){
        console.log(err);
    }

    var dados = results,
        usuario_encontrado = false;
    /// ; ^ inicializa dizendo que não encontrou usuário

    dados.forEach(function(row){
      if(row.email_cli == req.body.email_cli){
          usuario_encontrado = true;   
    /// ; marca como encontrado ^
      }
    });

    if( usuario_encontrado )
    {
        /// usuário já registrado
    }
    else
    {
        /// usuário não esta registrado
    }


  });

});


A simpler solution

  1. Make a query on your DB searching for the email informed.
    • If the query not return registration cadastra.
    • If the query return some record unregistered.

A possible start point:

router.post('/loginCli', function(req, res, next) {

    /// ; Você pode verificar se a senha repetida esta certa
    /// ; antes mesmo de fazer a query afinal não faz sentido 
    /// ; fazer nada se isso estiver diferente. 
    if(req.body.senha_cli != req.body.Csenha_cli) {

        return;
    }

    var query = "SELECT * FROM bdlabella.tbclientes WHERE email_cli = ? ORDER BY email_cli",
    /// ;            será preenchido pelo mysql com o valor informado ^ 
        where = [ req.body.email_cli ];
    /// ;                  ^ valor informado

    conn.query( query, where, (err, results) => {

        if(err){
            console.log(err);
        }

        if( results && results.length > 0 )
        {
            /// email já cadastrado
        }
        else
        {
            /// fazer o cadastro
        }
    });
});

About the break within the forEach

The break does not work within the forEach, to stop the cycle you can use a check with return or do the forEach within a block try/catch and fire an exception with the throw, See the example below:

try{
  [1,2,3,4,5,6].forEach( x=> {
      if( x > 2 ) throw "Termina";
      /// ;        ^ dispara a exception
      console.log(x);
  });
}catch(e){}
/// ;  ^ captura a exception para não travar o codigo

console.log("FIM");

Reference: Node.js Mysql Where

0

The problem is using the break within the forEach. If you want to stop the loop without iterating over all elements of the array, the ideal would be to simply use a for. In this case it would be possible to break the loop easily with break or return.

Reference: http://sajanmaharjan.com.np/2016/08/12/javascript-break-foreach/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.