I have an express app using fetch()
to delete files from a mongo database, using Mongoose.js
The problem is, that instead of redirecting after delete like it should, it gives me GET http://localhost:4545/article/delete/61232f8d604b6c8f3042f4f4 404 (Not Found)
as if it was sent as a GET request, which I don't understand. The weird thing is, the item actually does get deleted from the database, but the webpage doesn't redirect and instead displays an error:
Cannot GET /article/delete/61232f8d604b6c8f3042f4f4
Here's the fetch call in the client-side javascript. The delete button is not a member of a form.
const deleteBtn = document.querySelector('#DELETE');
deleteBtn.addEventListener('click', (event)=> {
const parts = event.target.href.split('/');
const id = parts[parts.length - 1];
fetch('/article/delete/' + id, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
})
.then(data => console.log(data))
.catch(error => console.log(error));
});
And then the delete method in Express JS:
app.get('/deleted', (request, response)=> {
response.render('deleted');
});
app.delete('/article/delete/:id', (request, response)=> {
Article.deleteOne({ _id: request.params.id}, (error)=> {
if(error) {
console.log(error);
} else {
response.redirect('/deleted')
}
});
});
Why isn't the fetch()
treating this request as a DELETE
? Looking at the network, it's being handled as a GET. How do I get it to handle a DELETE as a DELETE? I already have the method set in the fetch.
And if it's being handled as a GET, why is express still handling it and deleting the items from Mongo?