错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 headers。为什么?

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

我在 MognoDB 中保存图像文件时遇到问题。它说的是错误

(node:14849) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我搜索错误解决方法的时候,说是我在发送结果后才发送。我正在检查我的代码,它不是那样的。谁能帮我找出错误?

imageUpload.js

const multer = require("multer");
const uploadImage = require("../../models/fileUpload");

const Storage = multer.diskStorage({
  destination: "uploads",
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});

const upload = multer({
  storage: Storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
}).single("testImage");

const imageUpload = async (req, res) => {
  try {
    upload(req, res, (err) => {
      if (err)
        res.status(400).json({
          success: false,
          message: "Saving Failed",
        });

      const newImage = new uploadImage({
        name: req.body.name,
        image: {
          data: req.body.image,
          contentType: "image/png",
        },
      });

      newImage
        .save()
        .then(() => {
          res.status(201).json({
            success: true,
            msg: "Saved Successfully",
          });
        })
        .catch((error) => {
          res.status(500).json({
            success: false,
            msg: error.data,
          });
        });
    });
  } catch (err) {
    console.log(err);
  }
};

module.exports = { imageUpload };

return 在向客户端发送响应之前添加 return 在您发送的每个响应之前它将修复错误并且也是一个好习惯

我无法用 else 正确定义 if 条件。

Here is the code below rewritten.

imageUpload.js

const multer = require("multer");
const uploadImage = require("../../models/fileUpload");

// const Storage = multer.diskStorage({
//   destination: "uploads",
//   filename: function (req, file, cb) {
//     const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
//     cb(null, file.fieldname + "-" + uniqueSuffix);
//   },
// });

const upload = multer({
  // storage: Storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
}).single("testImage");

const imageUpload = async (req, res) => {
  try {
    upload(req, res, (err) => {
      if (err) {
        res.status(400).json({
          success: false,
          message: "Saving Failed",
        });
      } else {
        const newImage = new uploadImage({
          name: req.body.name,
          image: {
            data: req.body.image,
            contentType: "image/png",
          },
        });

        newImage
          .save()
          .then(() => {
            res.status(201).json({
              success: true,
              msg: "Saved Successfully",
            });
          })
          .catch((error) => {
            res.status(500).json({
              success: false,
              msg: error.data,
            });
          });
      }
    });
  } catch (err) {
    console.log(err);
  }
};

module.exports = { imageUpload };