Jquery Ajax删除调用返回404未找到

标签 jquery node.js

老实说,这真的让我很头疼。

这是我的 jquery 删除调用:

$(document).ready(function() {
    $(".deleteUser").on("click", deleteUser);
});

function deleteUser() {
    var id = $(this).data("id");
    var confirmation = confirm("are you sure?");
    if (confirmation) {
        $.ajax({
            type: "DELETE",
            url: "/users/delete/"+id
        });
    } else {
        return false;
    }
};

在我的 Node 中,我有这个:

app.delete("/users/delete/:id", (req, res) => {
    console.log("id sent:", req.params.id);
    res.send("get a delete call!");
});

显然, Node 文件远不止于此,但我只放了一部分。

当我单击应该启动删除的按钮时,出现错误:

DELETE http://localhost:3000/users/delete/ 404 (Not Found)

我在 postman 上运行了相同的 URL,并且得到了正确的响应!

那么,ajax什么时候会失败呢?我检查过一切似乎都正常。我什至去掉了确认位并直接调用删除,但我仍然收到相同的 404。

请问谁能发现错误吗?

编辑 删除 HTML 如下所示:

<ul>
    <% users.forEach((user) => { %>
    <li><%= user.name %> - <a href="#" class="deleteUser" data-id="<%= user.id %>">Delete</a></li>
    <% }) %>
</ul>

我正在使用 ejs。

最佳答案

http://localhost:3000/users/delete/

我认为您的id 为空。上面的 url 不是您的 Node 路由的有效请求,您应该在上面的 url 中传递 id。

主要问题可能出在您的 html 中,它呈现 user.id 的空白值

data-id="<%= user.id %>"

http://localhost:3000/users/delete/123

假设这是来自某个在 id 属性前添加下划线的持久性引擎,请尝试

data-id="<%= user._id %>"

关于Jquery Ajax删除调用返回404未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52242699/

相关文章:

php - 为什么这个 jQuery 幻灯片不能正常工作?

node.js - MeanJs:如何发布数据?为什么服务操作不触发?

javascript - ./src/components/BasicList.js 中的错误模块构建失败 : SyntaxError: Decorators are not officially supported

javascript - 如何在不使用剪贴板的情况下从网站复制原始文本

node.js - 当从kubernetes上托管的Docker容器中请求时,Nodejs Mongodb返回EHOSTUNREACH

jQuery 和 Internet Explorer (IE9) 问题

javascript - 如何在 jQuery serialize() 函数中包含按钮值?

javascript - 我怎样才能更有效地针对这种情况进行编程?

jquery ui 菜单显示为透明或位于其他元素后面。

node.js - grunt 异步函数的 Node 替代方案