NodeJS - jQuery DELETE Method

NodeJS - jQuery DELETE Method

本文关键字:Method DELETE jQuery NodeJS      更新时间:2023-09-26

我正在尝试在单击按钮时发送 DELETE 请求,但我不确定我的 jQuery 是否已设置,尽管使用了用于删除方法的路由,但我仍然收到 GET 请求错误Cannot GET /app/delete/1。我的jQuery是否在正确的轨道上,我如何防止这个GET请求?

路线:

appRoutes.route('app/delete/:testId')
    .delete(function(req, res){
        models.Test.destroy({
            where: {
                userId: req.user.user_id,
                testId: req.params.testId           
            }
        }).then(function(){
            res.redirect('/app');
        });
    });

链接:

<a href="/app/delete/{{test.testId}}" id="test-delete-link">Delete</a>

j查询:

<script type="text/javascript">
        $(document).ready(function() {
            $('#test-delete-link').click(function(){
                $.ajax({
                    type: 'DELETE',
                    url: '/app/delete/{{test.testId}}'
                });
            });
        });
    </script>

问题是当单击链接时,它会使用 GET .当您的链接被点击时,会发生两件事。

  • 触发click事件,jQuery 发送DELETE请求。
  • 浏览器将GET请求发送到同一路径,因为它是一个链接。

若要解决此问题,请将链接的 href 属性设置为 "javascript:void(0);" 。这样,单击链接除了 click 事件中指定的内容外,不执行任何操作。

作为旁注,我会将请求的路径从 /app/delete/:testId 更改为 /app/:testId .正如你所说的那样,现在的方式是多余的DELETE /app/delete/1.更 RESTful 的方法是 DELETE /app/1 .