Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!