Al Imran Hossain
Al Imran Hossain

Reputation: 205

How to solve- Cannot set headers after they are sent to the client

The first time I am getting this type of error. In console I get data. But when res.json() It shows null. How can I solve that?

const getClientDetails = async (req: Request, res: Response) => {
  const { clientId } = req.params;
  let foundClient = await Client.findOne({
    _id: clientId,
  });

  let foundOrders = await Order.find({
    ClientId: { $in: [foundClient._id] },
  });

  if (foundOrders) {
    foundOrders.map(async (item) => {
      const foundOrderItem = await OrderItem.findOne({
        OrderId: item._id,
      })
        .populate("ProductId")
        .populate("OrderId");
      console.log("data...", foundOrderItem);
      return res.json(foundOrderItem);
    
    });
  }

};

Upvotes: 0

Views: 49

Answers (2)

user3767285
user3767285

Reputation: 121

You are trying to send a response every time you loop over the map item. You Should return the foundOrderItem and after the map is done send that as a response.

 if (foundOrders) {
    const foundOrderItems = foundOrders.map(async (item) => {
      const foundOrderItem = await OrderItem.findOne({
        OrderId: item._id,
      })
        .populate("ProductId")
        .populate("OrderId");
      console.log("data...", foundOrderItem);
      return foundOrderItem;
    
    });
    res.json({foundOrderItems})
  }

Upvotes: 1

Ximaz
Ximaz

Reputation: 316

Can I see the line where you're using the getClientDetails function ? I think your return res.json(...) is in conflict with a line under the function call where you may have another res.send|sendFile|json|end.

Upvotes: 1

Related Questions