【问题标题】:How to solve- Cannot set headers after they are sent to the client如何解决 - 将标头发送到客户端后无法设置标头
【发布时间】:2022-01-10 21:55:00
【问题描述】:

我第一次遇到这种类型的错误。在控制台中我得到数据。但是当 res.json() 显示为空。我该如何解决?

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

};

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    我可以看到您使用 getClientDetails 函数的那一行吗?我认为您的 return res.json(...) 与函数调用下的一行冲突,在该行中您可能还有另一个 res.send|sendFile|json|end

    【讨论】:

    【解决方案2】:

    每次循环遍历地图项时,您都会尝试发送响应。 您应该返回 foundOrderItem 并在地图完成后将其作为响应发送。

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

    【讨论】:

    • 它返回空白数组
    猜你喜欢
    • 2019-02-28
    • 2021-06-18
    • 2022-01-14
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多