Home > Mobile >  Cannot set Header after already being sent // node express
Cannot set Header after already being sent // node express

Time:05-28

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

CodePudding user response:

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.

  • Related