【问题标题】:Cannot set headers after they are sent to the client'发送到客户端后无法设置标头'
【发布时间】:2021-09-11 01:39:30
【问题描述】:

我是 nodeJs 的新手,但我已经进行了研究以解决我的问题,但似乎我缺乏异步功能。 我找到了这个解决方案,但它不起作用,我将在下面发布: enter link description here

这是我的代码

 router.put("/placeOrder", [auth, isVerified, isExists], async (req, res) => {
  try {
    const productList = req.body; // body
    await Promise.all(
      productList.map(async (element) => {
        // compare between the inserted element and the store one here
        let getItemPrice = await Order.findOne({
          _id: element._id,
          buyerId: req.user._id,
          orderStatus: "PENDING",
        });
        if (!getItemPrice) {
          return res.status(400).json({
            status: "failed",
            message: "order not exists",
          });
        }

        getItemPrice.items.map(async (item) => {
          await Order.findOneAndUpdate(
            {
              "items.productId": item.productId,
            },
            {
              $set: {
                orderStatus: "ACTIVE",
                "items.$.itemStatus": "ACTIVE",
                paymentMethod: element.paymentMethod,
              },
            }
          );
        });
      })
     
    );
    res.status(200).json({
      message: "Order has placed",
    });
  } catch (error) {
    return res.status(400).json({
      status: "failed",
      message: error.message,
    });
  }

  // update documents
});

我正在尝试检查 Id 是否不存在于我的数组中,如果不存在只是通过 Id 不存在的错误,它工作正常,但它会在日志中保留打印错误: TypeError: Cannot create property 'Symbol(level)' on string 'Cannot set headers after they are sent to the client' 感谢您的时间和整理

【问题讨论】:

  • 它为不存在的每个项调用res.status(400).json(
  • 您可能调用 res.json 两次。只需在每个 res.json 之前添加一个 console.log('send') ,如果您看到两次日志,则需要确保只调用一次。
  • 我是否应该在那里进行回调并只打印一次。这会让它工作吗

标签: javascript node.js arrays mongodb mongoose


【解决方案1】:

您不能发送多个回复。

productList.map(async (element, i) => {
    // compare between the inserted element and the store one here
    let getItemPrice = await Order.findOne({
      _id: element._id,
      buyerId: req.user._id,
      orderStatus: "PENDING",
    });

    getItemPrice && getItemPrice.items.map(async (item) => {
      await Order.findOneAndUpdate(
        {
          "items.productId": item.productId,
        },
        {
          $set: {
            orderStatus: "ACTIVE",
            "items.$.itemStatus": "ACTIVE",
            paymentMethod: element.paymentMethod,
          },
        }
      );
    });
  }

【讨论】:

  • 是的,但是在这种情况下,我不会检查 _id: element._id, 是否存在。如何检查 _id: element._id, 是否存在,如果不存在,我想通过错误
猜你喜欢
  • 2018-05-25
  • 2021-06-27
  • 2021-06-18
  • 2020-11-14
  • 2020-09-05
  • 2019-02-06
  • 2020-05-20
  • 2020-11-02
相关资源
最近更新 更多