`
const data = [{'name': 'Apip'}, {'name': 'Rohmat'}, {'name': 'ujang'}]
data.forEach(function (response) {
res.json(response)
})
`
I did the code above it doesn't work and then it throws an error "Cannot set headers after they are sent to the client"
CodePudding user response:
You have to send the data in a batch:
const data = [{'name': 'Apip'}, {'name': 'Rohmat'}, {'name': 'ujang'}]
res.json(response)
See Why can't I use res.json() twice in one post request?
CodePudding user response:
If you want to just response the same array object, then you should write res.json(data).
const data = [{'name': 'Apip'}, {'name': 'Rohmat'}, {'name': 'ujang'}]
res.json(data)
But, if you are doing some check or modification within forEach to array object then it depend how you want the output.
const data = [{'name': 'Apip'}, {'name': 'Rohmat'}, {'name': 'ujang'}]
var modified_data = []
data.forEach(function (response) {
// DO SOME CHECK OR CHANGE IN THE ARRAY OBJECT
// modified_data.push(// Your modified data)
})
res.json(modified_data);
You are getting this error is because, you have already sent result in the body, and forEach is trying to set the header again.