Express return post

Asked

Viewed 1,145 times

1

Good afternoon,

I am having a problem in the return of POST on express, I wanted to register users using the following code :

router.post('/user', (req,res,next) =>{

  var obj =   {name:req.body.des_name,
              email:req.body.des_email,
              endereco:req.body.des_endereco,
              cep:req.body.num_cep,
              phone:req.body.num_phone,
              password:req.body.des_password}



        user.verifyUserTest(obj.name, function(err, rows) {
             if (rows.length > 0){
               res.send({res : "usuário já cadastrado"})
             }
             else{
              user.setUserByParams(obj,res)
              next()
              }
         })

},Function(obj,res){

res.send("ok")

})

I need to catch the return of VerifyUser to make an if if if user exists display an error message, and if it does not exist it calls the next by passing Obj as parameter so that the other function setUserByParams enter the user in the database.

the problem is that the console.log(user.verifyUser(obj,res)) is returning Undefined and I needed it to return the user or a full value of what I send to the POST

the other methods:

Midleware

function verifyUser(req,res){

  return con.query(`SELECT * FROM TB_USER WHERE des_name like "${req.name}"`,res)
}

Database/Query:

function query(sqlQry,res){
  connection.query(sqlQry,function (err,results,fields) {
    if(err){
      res.json(err)
    }else{
      console.log("Query Executada: "+ JSON.stringify(results))
      res.json(results)

    }
  })
}

Detail that the post sending and execution of the method is ok because it returns me the objects containing the user in POSTMAN including I put a log in the query (query executed:) that is returning me the query result correctly.

I appreciate the help, thank you!.

Code setUsersByParams:

function setUserByParams(req,res){

  return con.query(`INSERT INTO db_lifeapp.tb_user (des_name,
                                                    des_email,
                                                    des_endereco,
                                                    num_cep,
                                                    num_phone,
                                                    des_password)
                          VALUES ('${req.name}',
                                  '${req.email}',
                                  '${req.endereco}',
                                  ${req.cep},
                                  ${req.phone},
                                  '${req.password}')`,res)

      }

Uses the same database query call.

1 answer

1


You have to create asynchronous logic in that middleware to wait for the comic’s answer before calling the next. You can do it like this:

router.post('/user', (req, res, next) => {
  var obj = {
    name: req.body.des_name,
    email: req.body.des_email,
    endereco: req.body.des_endereco,
    cep: req.body.num_cep,
    phone: req.body.num_phone,
    password: req.body.des_password
  }

  user.verifyUser(obj.name, function(err, rows) {
    if (rows.length > 0) next();
    else user.setUserByParams(req, next)
  })
}, function(req, res){
   // esta função corre quando o `next` anterior for chamado 
   // e aqui o utilizador já estava ou está agora registado
   res.send('Ok!');
});

function verifyUser(name, cb) {
  con.query(`SELECT * FROM TB_USER WHERE des_name like "${name}"`, cb)
}

function query(sqlQry, cb) {
  connection.query(sqlQry, cb)
}

function setUserByParams(obj, cb) {
  con.query(`
    INSERT INTO db_lifeapp.tb_user (
       des_name, des_email, des_endereco, num_cep, num_phone, des_password
    ) VALUES (
      '${obj.name}', '${obj.email}', '${obj.endereco}', ${obj.cep}, ${obj.phone}, '${obj.password}')`, cb)
}

I think the logic of your code limits you.

So I changed my answer. What you have (in question) is the answer of this SELECT to be solved within dat function query with res.json(results) and so does not allow what you need.

Who should treat this result is the function that calls the query, because the funçãoquery` should be "blind" and only do what you are asked and return the result.

  • in case then would only have to add that part ? user.verifyUser(obj.name, Function(err, Rows){ if (Rows.length > 0) next(); Else res.send({err: 'Unregistered user'}); })

  • @Felipesangiorge I think you should change your code. Take a look at the comment I added in the answer.

  • So the logic is right now, I get the return and validate if the user already exists, the problem is that when it validates that the user does not exist, it follows the next, but returns me the error : <!DOCTYPE html>&#xA;<html lang="en">&#xA; <head>&#xA; <meta charset="utf-8">&#xA; <title>Error</title>&#xA; </head>&#xA; <body>&#xA; <pre>[object Object]</pre>&#xA; </body>&#xA;</html>

  • @Felipesangiorge I used {err: 'Utilizador não registado'} for example. I don’t know what you have on the client side/ajax waiting for that value. What you want to send/show if the user doesn’t exist?

  • the message is correct but is a backend when passes to the next it would have to register the user, but returns this error I sent you and does not register the user.

  • @Felipesangiorge ah, you want to add one INSERT instead of making a mistake? and after the INSERT then call the next()?

  • not in the case the function itself setUserByParams has already an Insert, even has been tested, this function calls an Insert passing an object as parameter and the values of this object are inserted in the query, the problem is that I think is not even calling the next, I tried to give a console before calling setUserByParams and does not rotate the console.

  • @Felipesangiorge ah, ok. Actually it makes me see an error in my answer that comes from your logic. Again, don’t do res.send() within specialized functions. Their role is to do a specific task and not give feedback to the customer. Puts the code of setUserByParams that update the response.

  • Opa put there, I created a method queryTest and verifyUserTest putting the parameters you passed in the answer, tried calling both query and query test and returned that error.

  • @Felipesangiorge take a look now

  • Now it worked @Sergio only gave an edited Routes, because if Rows >0 must run if the user exists then returns the message that already exists, otherwise runs the other function, but that ai Thank you very much ! , I will post as completed thanks!!! helped a lot!

  • @Felipesangiorge great!

Show 7 more comments

Browser other questions tagged

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