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

jaxagkaj  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(174)

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

  1. exports.fetchOne = (req, res) => {
  2. const _id = req.params.id;
  3. console.log("fetch One");
  4. try {
  5. collectionsModel.findById(_id).then((data) => {
  6. if (!data) {
  7. res.status(404).json({ message: "Data not found" });
  8. }
  9. console.log(data);
  10. res.send(data);
  11. });
  12. } catch (error) {
  13. console.log(error.message);
  14. }
  15. };

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

  1. node:internal/errors:490
  2. ErrorCaptureStackTrace(err);
  3. ^
  4. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


这是authUser中间件

  1. const authUser = (req, res, next) => {
  2. console.log("Auth middleware");
  3. if (
  4. req.headers &&
  5. req.headers.authorization &&
  6. req.headers.authorization.split(" ")[0] === "JWT"
  7. ) {
  8. jwt.verify(
  9. req.headers.authorization.split(" ")[1],
  10. process.env.JWT_SECRET,
  11. function (err, verifyToken) {
  12. if (err) {
  13. res.status(401).json({ message: "Invalid JWT Token" });
  14. }
  15. userModel
  16. .findById(verifyToken.id)
  17. .then((user) => {
  18. if (!user) {
  19. res.status(401).json({ message: "Invalid User" });
  20. }
  21. })
  22. .catch((err) => {
  23. res.status(500).json({ message: err.message || "Server Error" });
  24. });
  25. }
  26. );
  27. } else {
  28. res.status(403).json({ message: "Token not present" });
  29. }
  30. next();
  31. };


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

roqulrg3

roqulrg31#

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

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

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

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

展开查看全部

相关问题