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

264
Views
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 answers
Answer question

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 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!