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
fetch
returns aPromise
, so you shouldawait
that (as well as awaitingresponse.json()
after).Notes
This is how I would do handle the request.
JS