Error: "Can’t set headers after they are sent" on Node.js / Express

Asked

Viewed 13,414 times

2

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 in the validation that the user already exists I receive the return that it already exists, the application continues to work normally, but when I fall in the validation of new user, where I am informed that the user has been registered ( the same is registered in the base all right) but the error application and I get the following message : (I use 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.

  • 2

    That mistake happens when you do res.send twice for the same request. Take a look at user.setUserByParams if the res is not being used there.

  • Opa was just that, without realizing my database returned a res rsrs puts the answer for me to mark as completed.

1 answer

4


Recalling another question I saw that the code of 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 you’re sending res.send inside query and in user.setUserByParams(obj,res). You must remove those res.send of specialized functions such as a BD query as I suggested in the other reply.

So you should do:

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!"
        })
      });
    }
  })
})
  • I made this edition and ended up removing, I will leave the res.send of the bank only for get requests, that need to return the same values, Thank you very much!

Browser other questions tagged

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