meseret kifle
meseret kifle

Reputation: 1

when I tried to send a two or more json files in express. It shows an error "Cannot set headers after they are sent to the client"

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

Upvotes: 0

Views: 92

Answers (1)

Rajeshwaran P
Rajeshwaran P

Reputation: 69

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

Upvotes: 0

Related Questions