Skip to content

Keep getting a DELETE 400 (Bad Request) with my REST API

So, I’ve created a API and I’ve got my POST and GET requests working, but I’m can’t get the DELETE request to work. I keep getting a ‘DELETE http://localhost:3000/api 400 (Bad Request)’ error in the console.

Here is the delete section in my server file:

app.delete('/api', (request, response) => {
    database.remove({ _id: request }, {}, function(err, numRemoved) {});
});

Here is the button that executes the DELETE:

    document.body.addEventListener('click', function(event) {
        if (event.target.id == uid) {
            const options = {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: uid
            };
            fetch('/api', options);
        };
    });

It says that the bad request comes from fetch(‘/api’, options);, but I have no idea how to fix it! Can anyone help me?

Answer

The error may be due to the fact that delete request should not receive a json body, you should pass the uid as a path variable like:

app.delete('/api/:uid', (request, response) => {
    const uid = request.params.uid;
    database.remove({ _id: uid }, {}, function(err, numRemoved) {});
});

And change your call to:

    document.body.addEventListener('click', function(event) {
        if (event.target.id == uid) {
            const options = {
                method: 'DELETE',
            };
            const endpoint = `/api/${uid}`;
            fetch(endpoint, options);
        };
    });