在猫鼬中将标头发送到客户端后无法设置标头

时间:2019-11-02 11:49:37

标签: node.js mongodb express npm mongoose

每当我删除订单并尝试使用相同的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
      });
    });
});

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

每个呼叫只能发送一次回复

发送响应后,您将无法为“该请求” 发送另一个响应。

在这里,您要发送两个响应,一个响应为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 ,如ans之一所示。

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

        return;
    }