DEV Community

Himanshupal0001
Himanshupal0001

Posted on

ERROR: Cannot set headers after they are sent to client!!!

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set Headers after they sent to the client

If you encounter this error you probably calling the response in a loop. For example

app.get('/pokemon', async (req,res)=>{
for(let i=1;i<20;i++)
{
const response = await fetch(url);
const data = await response.json();
res.json(data);
}})

Enter fullscreen mode Exit fullscreen mode

For this simple solution is just add return before response. This will return the response out of the loop.

return res.json(data)

Top comments (2)

Collapse
 
tqbit profile image
tq-bit • Edited

Or you could try and call res.json(data) after the loop (return may lead to undesired behaviour in this case).

This particular error is often caused whenever you try to send a second response after the first one.

Collapse
 
himanshupal0001 profile image
Himanshupal0001

Thanks for the suggestion.