mongoose 错误[ERR_HTTP_HEADERS_SENT],为什么会出现此错误?

jaxagkaj  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(77)

尝试为我的项目添加身份验证时出现此错误。
该控制器具有认证用户的中间件。

exports.fetchOne = (req, res) => {
  const _id = req.params.id;

  console.log("fetch One");
  try {
    collectionsModel.findById(_id).then((data) => {
      if (!data) {
        res.status(404).json({ message: "Data not found" });
      }
      console.log(data);
      res.send(data);
    });
  } catch (error) {
    console.log(error.message);
  }
};

字符串
这里的问题是这个控制器工作正常时,身份验证中间件不保留,但它给出了这个错误.

node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


这是authUser中间件

const authUser = (req, res, next) => {
  console.log("Auth middleware");
  if (
    req.headers &&
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "JWT"
  ) {
    jwt.verify(
      req.headers.authorization.split(" ")[1],
      process.env.JWT_SECRET,
      function (err, verifyToken) {
        if (err) {
          res.status(401).json({ message: "Invalid JWT Token" });
        }

        userModel
          .findById(verifyToken.id)
          .then((user) => {
            if (!user) {
              res.status(401).json({ message: "Invalid User" });
            }
          })
          .catch((err) => {
            res.status(500).json({ message: err.message || "Server Error" });
          });
      }
    );
  } else {
    res.status(403).json({ message: "Token not present" });
  }

  next();
};


控制台正在打印数据和“fetch One”,但数据没有正确发送到客户端(React)。
我能为你做些什么?
我尝试在中间件中更改不需要的next(),现在认证中间件的底部有一个next(),但错误仍然相同。

roqulrg3

roqulrg31#

因为当没有数据时,你试图发送两次响应。

collectionsModel.findById(_id).then((data) => {
      if (!data) {
        res.status(404).json({ message: "Data not found" });
      }
      console.log(data);
      res.send(data);
    });

字符串
如果没有数据,则添加返回

collectionsModel.findById(_id).then((data) => {
      if (!data) {
        return res.status(404).json({ message: "Data not found" });
      }
      console.log(data);
      res.send(data);
    });

相关问题