0
votes

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) at ServerResponse.header (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:771:10) at ServerResponse.send (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:170:12) at ServerResponse.json (E:\download\react-native\chat app\backend\node_modules\express\lib\response.js:267:15) at E:\download\react-native\chat app\backend\routes\Routes.js:183:40 at processTicksAndRejections (internal/process/task_queues.js:93:5) { code: 'ERR_HTTP_HEADERS_SENT' }

The code:

app.post("/images", (req, res) => {
    const uname = req.body.userName;
    FreindRequest.find({ $and: [{ acceptance: "accept" }, { $or: [{ reciever: uname }, { sender: uname }] }] }).then(
        users => {
            if (users) {
                users.map(user => {
                    ImageModel.find({ $or: [{ userName: user.sender }, { userName: user.reciever }] }).then(user => {
                        if (user) {
                            res.json(user);
                        }
                        else {
                            res.json({ error: "error" })
                        }
                    }).catch(err => console.log(err));
                })
            }
            else {
                res.json({ error: "error" });
            }
        }
    ).catch(err => res.json({ error: "error" }));
});
1
why do you want to return a response for each user find query? If you do that how can you get the execution control back to execute the next user element? You are using res.json() so many places needlessly and that is what causing the problem. And why are you writing a post request to find the records, post request should save the data. I don't see anywhere in the code saving the data.kavigun

1 Answers

0
votes

You can send only one response for one request. So you should not use res.json() inside map function.

If you want to send multiple JSON . You can create an array inside an function and then push all the data and send res.json() after map function like below.

app.post("/images",async (req,res)=>{ 
  const uname=req.body.userName; 
  FreindRequest.find({$and:[{acceptance:"accept"},{$or:[{reciever:uname},{sender:uname}]}]})
  .then( users=>{ 
    if(users){ 
      let userImages = []
      await users.map(user=>{ 
        ImageModel.find({$or:[{userName:user.sender},{userName:user.reciever}]})
        .then(user=>{ 
          if(user){ 
            userImages.push(user)
          } else { 
            res.json({error:"error"}) 
          }
        })
        .catch(err=>res.json({error:"error"})); 
      })
      res.json(userImages)  
    } else { 
      res.json({error:"error"}); 
    }
  })
  .catch(err=>res.json({error:"error"})); 
});