skip to Main Content

I’m trying to delete entry [i] from Swagger API with a button.

function deleteWork(id) {
    fetch("http://localhost:5678/api/works/" + id, {
        method: "DELETE",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify( {
            "id": id
        })
    })
}

The following code is inside a for loop, that fetches images from the API and displays them. Every image has a delete button appended to it, and this is my attempt at making them work:

    DELETEBTN.addEventListener("click", () => {
                deleteWork([i])
            })

The console returns error 401, with this request payload:

{"id":[10]}

The DELETE URL is /works/{id}, and the only parameter it needs is the id of the item to be deleted.

I assume the issue is within the body?

2

Answers


  1. Chosen as BEST ANSWER

    Solved. It just needed an auth, Swagger uses Bearer:

        function deleteWork(id) {
        let jwt = localStorage.getItem("jwt")
        fetch("http://localhost:5678/api/works/" + id, {
            method: "DELETE",
            headers: {
                "Authorization": `Bearer ${jwt}`,
                "Content-Type": "application/json",
            }})
    }
    

  2. The Fetch API doesn’t send or receive cookies by default. For more detail please visit Using the Fetch API – Sending a request with credentials included

    function deleteWork(id) {
        fetch("http://localhost:5678/api/works/" + id, {
            credentials: "include",
            method: "DELETE",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify( {
                "id": id
            })
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search