没有ajax请求被发送到服务器

时间:2021-03-13 03:16:28

标签: node.js ajax

我正在从浏览器向服务器发送 ajax 请求,但是当我尝试这样做时,什么也没有发生。但是我在 Postman 应用程序中尝试过的同样的事情它工作得非常好。我能知道为什么在客户端它不工作而在后端它工作得很好吗?

这是下面的代码片段:

app.js

app.delete("/api/users/:id", (req, res) => {
  const id = req.params.id;

  Order.findByIdAndDelete(id)
    .then((data) => {
      if (!data) {
        res
          .status(404)
          .send({ message: `Cannot Delete with id ${id}. Maybe id is wrong` });
      } else {
        res.send({
          message: "User was deleted successfully!",
        });
      }
    })
    .catch((err) => {
      res.status(500).send({
        message: "Could not delete User with id=" + id,
      });
    });
});

文件.ejs

<a class="btn border-shadow delete"
   style="cursor: pointer;" 
   data-id=<%=row._id%> >
   <span class="text-gradient"><i class="fas fa-trash-alt"></i></span>
</a>

这里是我发送 ajax 请求的地方

if (window.location.pathname == "/dasboard") {
  console.log("This was deleted initially")
  $ondelete = $(".table td a.delete");
  $ondelete.click(function () {
    var id = $(this).attr("data-id");

    var request = {
      url: `http://localhost:8080/api/users/${id}`,
      method: "DELETE",
    };

    if (confirm("Do you really want to delete this record?")) {
      $.ajax(request).done(function (response) {
        alert("Data Deleted Successfully!");
        location.reload();
      });
    }
  });
}

0 个答案:

没有答案