Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading