skip to Main Content

`

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"

2

Answers


  1. 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?

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search