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:
JavaScript
x
4
1
app.delete('/api', (request, response) => {
2
database.remove({ _id: request }, {}, function(err, numRemoved) {});
3
});
4
Here is the button that executes the DELETE:
JavaScript
1
13
13
1
document.body.addEventListener('click', function(event) {
2
if (event.target.id == uid) {
3
const options = {
4
method: 'DELETE',
5
headers: {
6
'Content-Type': 'application/json'
7
},
8
body: uid
9
};
10
fetch('/api', options);
11
};
12
});
13
It says that the bad request comes from fetch(‘/api’, options);, but I have no idea how to fix it! Can anyone help me?
Advertisement
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:
JavaScript
1
6
1
app.delete('/api/:uid', (request, response) => {
2
const uid = request.params.uid;
3
database.remove({ _id: uid }, {}, function(err, numRemoved) {});
4
});
5
6
And change your call to:
JavaScript
1
10
10
1
document.body.addEventListener('click', function(event) {
2
if (event.target.id == uid) {
3
const options = {
4
method: 'DELETE',
5
};
6
const endpoint = `/api/${uid}`;
7
fetch(endpoint, options);
8
};
9
});
10