0

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?

Jonathan Kuhl
  • 699
  • 9
  • 23
  • 2
    No idea if it's the problem, but it doesn't make sense to send a `Content-Type` request header with a `DELETE` request (or any other request with no body). – T.J. Crowder Aug 23 '21 at 05:41
  • 1
    What sort of element is `deleteBtn`? What are its attributes? – Phil Aug 23 '21 at 05:43
  • Also, don't respond to API requests with a redirect. Let your SPA handle navigation. Using a redirect like this will mean `fetch` resolves with an entire HTML document – Phil Aug 23 '21 at 05:45
  • Re @Phil's question about the button: If that is a `button` element without `type="button"`, it defaults to `type="submit"`. If the button is in a `form`, that will submit the form based on the `form`'s attributes. So if you have `action="/article/delete"` on the form (and no `method` or `method="GET"`), that'll cause a GET... – T.J. Crowder Aug 23 '21 at 05:49
  • I was using an `a` tag rather than a button. That explains why it keeps doing `GET`. A few modifications to the markup and javascript and it works now. I was using a `CONTENT-TYPE` because I was getting frustrated while looking at other examples. – Jonathan Kuhl Aug 23 '21 at 05:51

0 Answers0