This is my code in the routes file
router.get('/api/', async function(request, response){
let entries = await Entries.find({}, function(error){
if(error) console.log(error);
});
let catArray = [];
entries.forEach(entry=>{
catArray.push(entry.category.id);
});
console.log(new Set(catArray));
let categories = [...new Set(catArray)];
categories.forEach(category=>{
Entries.find({"category.id":category},function(error,result){
if(error){
console.log(error);
}else{
response.send(result);
}
})
});
})
In the above code the API returns the JSON result as per the request but there's an error in the server console.. so I am not sure why or how to resolve it. This is the error
events.js:291
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:530:11)
at ServerResponse.header (/Applications/MAMP/htdocs/xxxx-server/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Applications/MAMP/htdocs/xxxx-server/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Applications/MAMP/htdocs/xxxx-server/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/Applications/MAMP/htdocs/xxxx-server/node_modules/express/lib/response.js:158:21)
at /Applications/MAMP/htdocs/xxxx-server/routes/entries.js:144:26
at /Applications/MAMP/htdocs/xxxx-server/node_modules/mongoose/lib/model.js:5065:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Emitted 'error' event on Function instance at:
at /Applications/MAMP/htdocs/xxxx-server/node_modules/mongoose/lib/model.js:5067:15
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Based on my this link on stackOverflow,
Error: Can't set headers after they are sent to the client
I understand that I am sending a response multiple times even though I seem to be doing it just once..
Question #1 If there's an error in the console how is the response being sent? (I haven't tried this on the browser.. it's on Postman that I am able to view the result)
Question #2 How do I resolve the error in the console?
Question #3 How do I know which line of code is doing this (Sending response without me doing it)?
Would appreciate some help me on fixing this and helping me understand how to avoid this for other functions.