skip to Main Content

The delete request using fetch on the site does not work. But in the server part, the delete request is triggered(http://127.0.0.1:8000/docs ).

show_posts_to_delete.html:

{% extends "shared/index.html" %}


{% block title %}
  <title>Delete posts</title>
{% endblock %}

{% block content %}
  <div class="container">
  <div class="row">
    <div class="col">
      <h1 class="display-5 text-center text-danger mb-3">Delete Posts</h1>
    </div>
    <div id="result" class="text-danger text-bold lead"></div>
  </div>

  <div class="row">
    <table class="table">
        <thead style="color: #fff;">
          <tr>
            <th scope="col">Title</th>
            <th scope="col">Image</th>
            <th scope="col">Text</th>
          </tr>
        </thead>
        <tbody style="color: #fff;">
          {% for post in posts %}
            <tr>
                <td>{{post.title}}</td>
                <td>{{post.image}}</td>
                <td>{{post.text}}</td>
                <td>{{post.id}}</td>
                <td><button class="btn btn-danger btn-sm" onclick="delete_post({{post.id}})">Delete</button></td>
            </tr>
          {% endfor %}
        </tbody>
    </table>
  </div>
</div>
{% endblock %}


{% block scripts %}
<script type="text/javascript">
    async function delete_post(id){
        const response = fetch(`/posts/delete/${id}`,{  <-- **It is in this part of the problem**
            method: 'DELETE',
            headers: {
              "Content-Type": 'application/json'
            },         
            })
        const data = await response.json()
        .then(document.getElementById('result').innerHTML = "Refreshing...")
        .then(data => document.getElementById('result').innerHTML = data.detail);
    }
</script>
{% endblock %}

show_posts_to_delete.py:

@router.get("/delete-post/")
def show_posts_to_delete(request: Request, db: Session = Depends(get_db)):
    posts = list_posts(db=db)
    return templates.TemplateResponse(
        "posts/show_posts_to_delete.html", {"request": request, "posts": posts}
    )

delete_post.py:

@router.delete("/delete/{id}")
async def delete_post(
    id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user_from_token),
):
    post = retreive_post(id=id, db=db)
    if not post:
        return HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Post with id {id} does not exist",
        )
    print(post.owner_id, current_user.id, current_user.is_superuser)
    if post.owner_id == current_user.id or current_user.is_superuser:
        delete_post_by_id(id=id, db=db, owner_id=current_user.id)
        return {"detail": "Successfully deleted."}
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED, detail="You are not permitted!!!!"
    )

I removed the asynchronous function, used it ".then(response => response.json())" instead of "const data = await response.json()", but to no avail.

2

Answers


  1. fetch returns a Promise, so you should await that (as well as awaiting response.json() after).

    const response = await fetch(`/posts/delete/${id}`, {
        method: 'DELETE',
        headers: {
            "Content-Type": 'application/json'
        },
    });
    const data = await response.json();
    // use data after...
    document.getElementById('result').innerHTML = data.detail;
    
    Login or Signup to reply.
  2. Notes

    This is how I would do handle the request.

    JS

    async function delete_post( id ){
        // Find the element once
        const resultElement = document.getElementById('result');
    
        // Overwrite html with spinner
        resultElement.innerHTML = "Refreshing...";
    
        // Request delete from server
        const response = await fetch(`/posts/delete/${id}`,{ 
                method: 'DELETE',
                headers: {
                "Content-Type": 'application/json'
                },
            });
    
        // Get server response
        const data = await response.json();
    
        if ( data.ok === true ){
            // Handle Success
            resultElement.innerHTML = data.detail;
            return data.detail;
        } else {
            // Handle Failed
            resultElement.innerHTML = 'Something went wrong';
            console.error( new Error( 'Something went wrong' ) );
            return null;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search