I can’t delete a work from an API. According to the swagger, you have to use the ID to delete the work. I wrote the code but it does not work I have an error message in the console 401. Here is the github link to see eventually all the code in adminscript.js : https://github.com/mjandia/Portfolio-architecte-sophie-bluel
If you have a solution or if you see an issue in my code, thanks for your help.
Here is the swagger infos :
DELETE /works/{id} Delete a work depending on id
Parameters
Try it out
Name Description
id *
integer($int64)
(path)
id of work to be deleted 1
Here is the javascript code :
/* Load data from API to admin.html page */
const gallery = document.querySelector(".gallery");
const portfolio = document.getElementById("#portfolio");
fetch("http://localhost:5678/api/works")
.then(response => {
if (response.ok) {
return response.json();
}
else {
throw new Error('Il y a une erreur');
}
})
.then(works => {
for (let i = 0; i < works.length; i++) {
let work = works[i];
let div = document.createElement("div");
div.innerHTML = work.title;
div.setAttribute("data-id", work.id);
div.setAttribute("data-user-id", work.userId);
gallery.appendChild(div);
let img = document.createElement("img");
img.src = work.imageUrl;
div.appendChild(img);
img.crossOrigin = "anonymous";
}
});
/* Delete the gallery */
const deleteGalleryButton = modal3.querySelector(".delete-gallery");
deleteGalleryButton.addEventListener("click", function(event) {
const id = event.target.parentElement.dataset.id;
const div = event.target.parentElement;
let userId = div.dataset.userId;
fetch(`http://localhost:5678/api/works/${id}`, {
method: "DELETE",
headers: {
"Authorization": `Bearer ${userId}`,
},
})
.then(response => {
if (!response.ok) {
throw new Error("Erreur 200")
}
return response.json();
})
.then(data => {
modal3.querySelector("p").innerHTML = "";
})
.catch(error => {
console.error("Problème Fetch", error);
});
});
I’m a beginner and thanks for your help. Here is the image of the console :