首页 > 解决方案 > axios.delete() 未运行然后阻塞

问题描述

我有一个带有 react、express 和 mongo 的小应用程序。GET 和 POST 请求在 axios 上工作得很好。DELETE 请求与后端一起工作,实际上删除了 mongo 数据库中的项目。代码片段:

 deleteTodo = (event) => {
    const url = "http://localhost:4000/dashboard";
    const id = event.target.parentElement.getAttribute("data-id");
    const deleteUrl = `${url}/${id}`;

    axios.delete(deleteUrl)
        .then(res => {
            console.log("deleted")
        });
}

但是之后什么都没有发生,我没有在控制台中收到“已删除”消息。我尝试了console.log、setState等,这些函数都没有在.then中触发。

标签: reactjsexpressaxioshttp-delete

解决方案


我在 server.js 的 delete 方法中更改了代码,现在它以某种方式工作。从:

app.delete("/dashboard/:id", (req, res) => {
  const id = req.params.id;
  Item.findById(id)
    .then(item => item.remove())            
});

至:

app.delete("/dashboard/:id", (req, res) => {
  const id = req.params.id;
  Item.findById(id)
    .then(item => item.remove()
        .then(() => res.json({ success: true })))
    .catch(err => res.send("Error"))
});

推荐阅读