Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

546
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda