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);
}})
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)
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.
Thanks for the suggestion.