sqlite 使用fetch删除帖子的问题

pwuypxnk  于 2023-08-06  发布在  SQLite
关注(0)|答案(3)|浏览(129)

在网站上使用fetch的删除请求不起作用。但是在服务器部分,删除请求被触发(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!!!!"
    )


我删除了异步函数,使用它“.then(response => response.json())”而不是“const data = await response.json()”,但没有用。

r7xajy2e

r7xajy2e1#

fetch返回一个Promise,所以你应该await(以及等待response.json()之后)。

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;

字符串

dphi5xsq

dphi5xsq2#

如何处理请求:

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;
    }
}

字符串

e5nqia27

e5nqia273#

我解决了这个问题,问题就跟代币一样...我非常感谢所有帮助我解决问题的人!)

相关问题