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

260
Visualizações
Express: res.json for Array

I want to do the following:

uploads.forEach(function(object){
  res.json({
    sessionId: object.sessionId,
    fileId: object.id,
    path: `${baseUrl}/sessions/${object.sessionId}/files/${object.id}/tokens`
  });
});

My response looks good so far:

{
  "sessionId": "9ff1c415-2dcc-4505-8414-4391967064bc",
  "fileId": "510647c3-62fc-4412-b189-a6b872606f10",
  "path": "http://localhost:3001/sessions/9ff1c415-2dcc-4505-8414-4391967064bc/files/510647c3-62fc-4412-b189-a6b872606f10/tokens"
}

But I get an error in my console:

Error: Can't set headers after they are sent.

So how do I avoid that error?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

res.json will end the request/response cycle so I don't believe you can put this in a forEach as this will attempt to issue a response after one has already fired.(Thats why the error about the headers because they were sent during the first iteration of the for loop and the next iteration trys to change them which isn't allowed because they aren't there anymore -- the response already left for the client)

Instead try filling an Array of objects in your 'forEach'. then pass this into your response object outside of the loop.

    var data = []
    uploads.forEach(function(object){
      data.push({
        sessionId: object.sessionId,
        fileId: object.id,
        path: `${baseUrl}/sessions/${object.sessionId}/files/${object.id}/tokens`
      });
    });
    res.json(data);
about 4 years ago · Santiago Trujillo 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