It doesn’t work because you’re not responding to the request. Compare your post route with the get one; in the latter, you’re responding with res.json(data), whereas the others don’t have any.
Is fine, but if there’s actually an error, you will be answering with the same response regardless. What you should do is:
if (err) {
console.error(err);
return res.status(500).json({ error: 'Database operation failed' });
}
// Here you process the successful response
res.json(data);
I see… the problem you have now is that you’re not awaiting for the save to finish, hence the newIssue may or may not be saved when you send the response.
You should use async/await for all your database calls:
.post(async function(req, res) {
// Removed the rest of the code just to make it clearer
newIssue = new Issue(newIssue);
// When using async/await, you need to add try/catch blocks
// to handle errors, otherwise they may leak information
// to the client. You could catch them later though.
try {
// After saving it, the newIssue will have an _id
newIssue = await newIssue.save();
res.json(newIssue);
} catch (error) {
console.error('Error saving issue:', error);
return res.json({ error: 'Could not save the issue' });
}
})
One thing I didn’t mention is that async/await is not the only option, since you can pass a callback or use Promises.
Here are examples for doing the same as before with Promises and callbacks:
Using Promises
.post(function(req, res) {
newIssue = Issue(newIssue);
newIssue.save()
.then(savedIssue => res.json(savedIssue))
.catch(e => {
console.error('Error saving issue:', e);
return res.json({ error: 'Could not save the issue' });
});
});
Using Callbacks
// This is the one you may know best
.post(function(req, res) {
newIssue = Issue(newIssue);
newIssue.save((error, savedIssue) => {
if (error) {
console.error('Failed to save issue:', error);
return res.json({ error: 'Could not save the issue' });
}
res.json(savedIssue);
});
});
I can DELETE/api/issues/{projectName} with an _id to completely delete an issue. If no _id is sent return ‘_id error’. Return ‘Deleted {_id}’ if you successfully delete an issue, and ‘Could not delete {_id}’ if you could not.
Hence your delete method should return Deleted ID, where ID is the req.body._id.
Try to fix the issues and let us know how it goes .