Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
Cannot set Header after already being sent // node express

I am prompted with cannot set headers after they are already being set. My code intercept for put method sent on the URL it then checks for missing id, after that checks if no field inputted is undefined it then perform try-catch method within which it updates for given id. If the id is not correct then it responds with an error. My code is :

.put(async function (req, res){
  console.log(req.body._id + " is id.")
  const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
  if(!_id){
    res.json({error: "missing _id"})
  }
  
  const fields = {issue_title, issue_text, created_by, assigned_to, status_text, open}
  const checkAllUndefined = Object.values(fields).every(val => (val == undefined || val == '')? true: false)  
  
  if(checkAllUndefined){
    res.json({ error: 'no update field(s) sent', _id})
  } else{ 
     try{
       await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {$set:    
       {issue_title,issue_text,created_by, assigned_to, status_text, open, 
          updated_on: new Date()}}, {
          new: true,
          omitUndefined: true
            })
        res.json({  result: 'successfully updated', _id})
       }catch(err){
        res.json({ error: 'could not update', _id})
       }
    }     
  })
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your first If statement is returning the response if _id is undefined !

if(!_id){
    res.json({error: "missing _id"})
  }

After sending this response your next if block or its else block gets executed which leads to sending another response which is not possible or allowed !, You have to nest if else block like this

   

    put(async function (req, res) {
    console.log(req.body._id + " is id.")
    const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
    if (!_id) {
        res.json({error: "missing _id"})
    } else {
        if (checkAllUndefined) {
            res.json({error: 'no update field(s) sent', _id})
        } else {
            try {
                await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {
                    $set:
                        {
                            issue_title, issue_text, created_by, assigned_to, status_text, open,
                            updated_on: new Date()
                        }
                }, {
                    new: true,
                    omitUndefined: true
                })
                res.json({result: 'successfully updated', _id})
            } catch (err) {
                res.json({error: 'could not update', _id})
            }
        }
      }
    )
    }

by doing this you are only sending response only once.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda