This is my source code to delete a specific id:
router.delete('/api/items/:id', async (req, res) => {
res.json(req.params.id);
try {
const deleteItem = await todoItemModel.deleteOne({ id: req.params.id });
res.status(200).json('Item deleted successfully');
} catch (err) {
res.json(err);
}
})
RESTful Client:
DELETE http://localhost:5000/api/items/62f9ce3acb74841984127399 Content-Type: application/json
Error detail:
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:\Users\thait\Projects\todo-list-mern\server\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\thait\Projects\todo-list-mern\server\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (C:\Users\thait\Projects\todo-list-mern\server\node_modules\express\lib\response.js:278:15)
at C:\Users\thait\Projects\todo-list-mern\server\src\routes\items.js:26:13
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
CodePudding user response:
Try to remove this line.
res.json(req.params.id);
CodePudding user response:
Can you please try once with this code?
router.delete('/api/items/:id', async (req, res) => {
res.json(req.params.id);
try {
const deleteItem = await todoItemModel.deleteOne({ _id: req.params.id });
return res.status(200).json('Item deleted successfully');
} catch (err) {
return res.status(500).json({err});
}
})