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?
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);