【问题标题】:Issue with Error 404 on delete request only仅在删除请求时出现错误 404
【发布时间】:2019-12-06 23:18:07
【问题描述】:

节点 JS 的新手,遇到删除请求返回 404 未找到的问题。我可以正常连接到数据库,能够通过发布请求添加到数据库中,只有删除请求才会导致问题。这是来自我的控制器文件:

app.delete('/:item', function(req,res)
    {
        steTodo.find({item:req.params.item.replace(/\-/g, " ")}).remove(function(err,data)
        {   
            if(err) throw err;
            res.json(data);
        });

这是jquery:

$('.removeClass').on('click', function()
    {
        var item = $(this).text().replace(/ /g, "-");
        $.ajax({
          type: 'DELETE',
          url: '/' + item,
          success: function(data)
          {

            //do something with the data via front-end framework
            alert('Successfully called');
            location.reload();
          },
          error: function(jqxhr, status, exception)
          { 
            alert('Exception:', status);
          }
        });      
    });

这是我在控制台中看到的错误:

jquery.min.js:2 DELETE http://localhost:3000/get-flowers 404 (Not Found)

任何想法或想法将不胜感激。

【问题讨论】:

    标签: jquery node.js ejs


    【解决方案1】:

    改变你的路线:

    app.delete('/delete/:item', function(req,res) { ... }
    

    在 Ajax 函数中:

      $.ajax({
          type: 'DELETE',
          url: '/delete/' + item,
          ...
       });
    

    【讨论】:

    • 您好抱歉延迟回复。我试过了,不幸的是它对我不起作用。
    • 打开检查元素,检查网络选项卡,确保您的 AJAX 请求发送到服务器?
    【解决方案2】:

    它看起来像是调用 get-flowers 路由,而不是将其视为 url 参数。

    如果你改成这个。

    app.delete('/', function(req,res)
        {
          const { query } = req;
          const { item } = query;
            steTodo.find({item:item.replace(/\-/g, " ")}).remove(function(err,data)
            {   
                if(err) throw err;
                res.json(data);
            });
    
    

    和这样的ajax调用,

    $.ajax({
              type: 'DELETE',
              url: '/?item=' + item,
              success: function(data)
              {
    
                //do something with the data via front-end framework
                alert('Successfully called');
                location.reload();
              },
              error: function(jqxhr, status, exception)
              { 
                alert('Exception:', status);
              }
            });      
    

    它现在应该可以工作了。

    【讨论】:

    • 抱歉延迟回复并感谢您的帮助,但这对我没有用。我仍然在 chrome 控制台中收到错误:jquery.min.js:2 DELETE localhost:3000/?item=get-flowers 404 (Not Found)
    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2016-03-29
    • 2018-05-27
    相关资源
    最近更新 更多