【问题标题】:Cannot set headers after they are sent to the client in Mongoose将标头发送到 Mongoose 中的客户端后无法设置标头
【发布时间】:2020-02-28 10:22:15
【问题描述】:

每当我删除我的订单并尝试使用相同的 id 再次获取时 它返回一个正确的响应(未找到订单),但在控制台中它返回一个错误

router.delete("/:orderID", (req, res, next) => {
  const id = req.params.orderID;
  Orders.deleteOne({ _id: id })
    .exec()
    .then(result => {
      if (!result) {
        res.status(404).json({
          message: "there is no such Order to Delete, Kindly Check Order ID",
          fetchAll: "http://localhost:3000/orders/"
        });
      }
      res.status(200).json({
        message: "Order Deleted Successfully",
        request: {
          type: "POST",
          url: "http://localhost:3000/orders/",
          body: {
            productID: "Id of the Product",
            quantity: "Total Quantity of the Product"
          }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

【问题讨论】:

    标签: node.js mongodb express npm mongoose


    【解决方案1】:

    您需要在发送 404 后返回,否则您先发送 404,然后再发送 200。因为代码将继续运行。

    if (!result) {
      res.status(404).json({
        message: "there is no such Order to Delete, Kindly Check Order ID",
        fetchAll: "http://localhost:3000/orders/"
      });
      return;
    }
    

    【讨论】:

    • DELETE /orders/5dbd5c94f15dce21b4859659 200 117.300 ms - 188 错误 [ERR_HTTP_HEADERS_SENT]:在 ServerResponse.header 的 ServerResponse.setHeader (_http_outgoing.js:470:11) 将标头发送到客户端后无法设置标头(C:\Users\Manav\Documents\Github\RESTful-
    【解决方案2】:

    每次通话只能发送一次回复

    一旦发送了响应,您就不能为“那个请求”发送另一个响应。

    在这里,您发送两个响应,一个带有 200(成功场景),另一个带有 404(错误场景)。

    由于这是针对两种不同目的的两种不同响应,

    将它们保存在 if else block 中,如下所示:

        if (!result) {
            res.status(404).json({
              message: "there is no such Order to Delete, Kindly Check Order ID",
              fetchAll: "http://localhost:3000/orders/"
            });
        } else {
          res.status(200).json({
            message: "Order Deleted Successfully",
            request: {
              type: "POST",
              url: "http://localhost:3000/orders/",
              body: {
                productID: "Id of the Product",
                quantity: "Total Quantity of the Product"
              }
            }
          });
        } 
    

    或者只是 return 如其中一个答案所示。

        if (!result) {
            res.status(404).json({
              message: "there is no such Order to Delete, Kindly Check Order ID",
              fetchAll: "http://localhost:3000/orders/"
            });
    
            return;
        } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2019-05-17
      • 2022-01-14
      • 2021-04-07
      相关资源
      最近更新 更多