Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
Error with async code design. UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT],

I am facing an error with node/express. I am assuming the issue is with my asynchronous code design.

Output: Success in container

Expected Output: Success in container.. Success in Uploading...

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

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Code:

const express = require("express");
const multer = require("multer");
const AuthReq = require("../middleWare/AuthReq");
require("dotenv").config();
const Azure_Storage_Connection_String = process.env.Azure_Connection_String;
const { BlobServiceClient } = require("@azure/storage-blob");

const Router = express.Router();

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

Router.post("/profile", AuthReq, upload.single("profile"), async (req, res) => {
  const file = req.file;

  const blobServiceClient = BlobServiceClient.fromConnectionString(
    Azure_Storage_Connection_String
  );

  const containerName = req.user._id;

  const ContainerClient = blobServiceClient.getContainerClient(containerName);

  try {
    const containerResponse = await ContainerClient.create();
  } catch (err) {
    return res.status(400).send("Error while sending image");
  }

  res.send("Success in container");

  const contentType = file.mimetype;

  const filePath = file.path;

  const blobName = file.filename + contentType;

  const blockBlobClient = ContainerClient.getBlockBlobClient(blobName);

  try {
    const uploadBlobResponse = await blockBlobClient.uploadFile(filePath);
  } catch (err) {
    return res.status(400).send("Error while sending image");
  }

  res.send("Success in Uploading...");
});

module.exports = Router;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You cannot use res.send more than once per request, because one request has only one response. I assume that you want to send a "two-part" response, so that the user first sees "Success in container" and then (a few seconds later) "Success in Uploading ...".

Node.js will send the response in two "chunks" if you use

res.write("Success in container");
...
res.end("Success in Uploading...");

(See also the explanation in this answer.)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda