Can't delete work from an API - javascript

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 :

I cloned your repo, started the backend server, but I am unable to login with the username and password shown in the repo.

It is strange because i can. Do you use the main branch because the master it is not up to date. I pushed last work there is 10mn maybe after you tried. Could you try again please?

I did not know the working code was on main. I am able to log in now. How do I replicate the issue? I assume I go to the admin.html page.

yes you log in with the loggin link and credentials given in repo readme. and you click on “modifier” link (modify) next to “Mes Projets”, a modal window open and click to “supprimer la galerie” (delete gallery) and the console show the issue. thank for your help. I was eating, sorry for the delay

If the id is undefined (in the console) I would assume this

event.target.parentElement.dataset.id

isn’t getting the value. What element is it you believe it is selecting?

<aside id="modal3" class="modal" aria-hidden="true" role="dialog">
	<div class="modal-wrapper modal-close">
		<div class="galleryModal3">
		</div>
		<button class="btn">Editer</button>
			<ul class="photo">
				<li><a class="linkphoto" href="#" role="button" data-target="#modal5" data-toggle="modal">Ajouter une photo</a></li>
			</ul>
			<ul>
				<li class="delete-gallery">Supprimer la galerie</li>
			</ul>
	</div>
</aside>
let modal3 = document.getElementById("modal3");
// other code

const deleteGalleryButton = modal3.querySelector(".delete-gallery");

deleteGalleryButton.addEventListener("click", function(event) {
    const id = event.target.parentElement.dataset.id;
	// rest of code
}

I think that : event.target.parentElement.dataset.id

select id, no ?

event.target.parentElement is targeting the ul element that contains the list element with the text “Supprimer la galerie”.

It would seem you have data-id attributes on the div elements located within the div with class="gallery", but you would need to have a Delete button for each div that when clicked would do what you want.

in fact I’m trying to have a function that deletes the gallery by referring to the work and the id

Does each div within the div with class="gallery" constitute a gallery or is the entire collections of those div elements the gallery? It is not clear based on your replies.

You only have a single button that gives no reference to which div you want to delete.

In fact. the class gallery in html include all photos and title with div for photo and div for title. I try to delete with the class gallery

So you want to delete the entire collection when Supprimer la galerie is clicked or just a specific photo?

With supprimer la galerie i want to delete all photosand their titles

Since the entire gallery is what you want to delete, then just remove the div class="gallery" element and delete all the works from the database in a single command. There is no need to worry about an id, since you are wanting to remove all of them.

I don’t understand why you would not want to be able to delete a single photo instead of all of them. I would want the ability for the admin to delete a single photo (work) by clicking on it and a pop up would show that allows the admin to edit the work title, change photo of the work, or delete the work.

Ok. I’m going to try

it’s planned to delete each photo individually but I haven’t started coding or adding the buttons yet. at the moment i don’t really know how to go about it

For add photo it is planned to click on “ajouter une photo” (add a photo) but it is in an other modal. You can click on “ajouter une photo” and you will see i’ve worked already a few on that function

I would avoid storing the images like:

http://localhost:5678/images/abajour-tahina1651286843956.png

in the database. I would store just the image name abajour-tahina1651286843956.png and then write your backend code to properly serve the images from whatever folder you choose to store them. Otherwise, you would need to do a massive update to the database if you ever moved the images to a different location (i.e. port).

I understand but the exercise is like that with the backend given, i work only on the frontend. Thank a lot for your help