Error: "Can not set headers after they are sent" in Node.js / Express

1

I have the following method:

//USER_POST
  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){
                   res.send({res : "usuário já cadastrado"})
                 }
                 else{
                  user.setUserByParams(obj,res)
                    res.send({res: "usuário cadastrado com sucesso!"})
                  }
             })
  })
When I fall into validation that the user already exists I get the feedback that it already exists, the application continues to work normally, but when I fall into the validation of a new user, where I am informed that the user has been registered (the same is registered in the base all right) but the application of the error and I get the following message: (I use the postman to test)

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
    at ServerResponse.header (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\express\lib\response.js:267:15)
    at Query._callback (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\config\database.js:23:11)
    at Query.Sequence.end (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at Query._handleFinalResultPacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
    at Query.OkPacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\sequences\Query.js:72:10)
    at Protocol._parsePacket (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Protocol.js:279:23)
    at Parser.write (C:\Users\felipe.sangiorge\Desktop\ProjetoAPP\Backend\node_modules\mysql\lib\protocol\Parser.js:76:12)
[nodemon] app crashed - waiting for file changes before starting...

Thanks for the help.

    
asked by anonymous 17.10.2017 / 15:59

1 answer

1

Remembering another question I saw that the code is:

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);
}

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)
    }
  })
}

What happens is that you are sending res.send within query and user.setUserByParams(obj,res) . You should remove these res.send of specialized functions as a query to BD as I suggested in the other answer .

So you should do it:

function query(sqlQry, cb) {
  connection.query(sqlQry, cb);
}
//USER_POST
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) {
      res.send({
        res: "usuário já cadastrado"
      })
    } else {
      user.setUserByParams(obj, function(err) {
        if (err) console.log(err); // eventualmente avisar com res.send também
        else res.send({
          res: "usuário cadastrado com sucesso!"
        })
      });
    }
  })
})
    
17.10.2017 / 16:33