django 404(Not Found)Not Found Not Found Not Found Not Found Not Found Not Found Not Found意外的标记“|”,“< !DOCTYPE“... is not valid JSON Promise.then(async)

u3r8eeie  于 2023-05-08  发布在  Go
关注(0)|答案(1)|浏览(185)

我使用Django-REST-Framework创建了一个API。当我发送DELETE请求到我的API时,我在尝试删除对象时遇到了问题。这是我的后端。
urls.py

urlpatterns = [
    path('getFavourite/', views.getFavourites),
    path('addFavourite/', views.addFavourites),
    path('deleteFavourite', views.deleteFavourites),
]

还有这个views.py

@api_view(['GET'])
def getFavourites(request):
    favourites=Favorite.objects.all()
    serializer=FavouriteSerializer(favourites , many=True)

    return Response(serializer.data)

@api_view(['DELETE'])
def deleteFavourites(request):
      name=request.data['name']
      favorite=Favorite.objects.get(name=name)
      favorite.delete()
      result="Your favorite has been deleted"
    
      return Response({"result":result})

这是我的前端:

let newContent=document.getElementById('favorite');

fetch("http://127.0.0.1:8000/getFavourite/")
.then(response => response.json())
.then(data => {
    for(i=0; i<data.length; i++){
        newContent.innerHTML += `<div class="container">
                                     <div style="">
                                          I do ${data[i].name} every  ${data[i].timeOfDoing} days
                                          <div onclick="favDelete('${data[i].name}')" 
                                               class="deletion-sign">&#9747;</div>
                                     </div>
                                 </div>`
                                 }
                })

function favDelete(name){
    console.log(name)
    fetch("http://127.0.0.1:8000/deleteFavourite/" , {
        method:"DELETE",
        headers: {
            'Content-Type' : 'application/json'
        },
        body:JSON.stringify({"name":name})
    })
    .then(response => response.json())
    .then(data => console.log(data.result) )

}

尝试此代码时,我在控制台中看到以下错误:

DELETE http://127.0.0.1:8000/deleteFavourite/ 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Promise.then (async)

我成功地使用POST请求添加了对象,但无法使用DELETE方法删除对象。有没有人好心地告诉我,我是不是忘了做某件事或者做错了什么事?

8ehkhllq

8ehkhllq1#

感谢[1]:https://stackoverflow.com/users/8678978/chrisbyte我记得我们应该用斜杠来 Package url的结尾。所以我的urls.py应该是这样的:

**urlpatterns = [
                  path('deleteFavourite/', views.deleteFavourites),
                    ]**

相关问题