I am trying to use Fetch
in my React
component, but I am not sure that I understand well the syntax. Currently I am using Ajax
with jQuery
:
handleDeleteProject(projectID) {
$.ajax({
url: './comments/delete',
data: { productID: projectID },
type: 'get',
cache: true,
success: function (response) {
console.log("ok");
},
});
}
And I want to convert it to Fetch
. Right now I have somethinkg like that, but it does not work. Event does not go through breakpoint in server's controller:
fetch('./comments/delete', {
method: 'get',
body: "productID=" + encodeURIComponent(projectID)
})
.then(res => res.json())
.then(res => {
console.log('usunąłęm produkt:');
console.log(res);
})
You don't want to send the productID
in the body of the request, but as a query parameter. You also don't have to specify the method, since GET
is the default.
fetch("/comments/delete?productID=" + encodeURIComponent(projectID))
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
Off topic: You most likely don't want to delete resources with a GET
request. Look into changing it to a DELETE
request instead.