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

I am having a issue while saving the image file in MognoDB. It is saying the error

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

While I searched for the error solution, it was said that I am sending the result after it is sent. I am checking my code it is not like that. Can anyone help me with this to find the error please?

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 };



Solution 1:[1]

I couldn't properly defined the if condition with else.

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 };

Solution 2:[2]

return before sending response to client add return before every response you sent it will fix the error and also its a good habbit

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fzee
Solution 2 Mubasher Ali