2017-07-11 57 views
0
我無法在我的view.My視圖中單擊按鈕刪除在我的數據庫中的文檔

看起來是這樣的:刪除文件,404沒有找到DELETE方法

extends layout 

block content 
    h1 #{article.title} 
    h5 Written by #{article.author} 
    p #{article.body} 
    hr 
    a.btn.btn-default(href='/article/edit/'+article._id) Edit 
    a.btn.btn-danger.delete-article(href='#',data-id=article._id) Delete 

,我的js文件與AJAX:

$(document).ready(function() { 
$('.delete-article').on('click', function (e) { 
    $target = $(e.target); 
    const id = $target.attr('data-id'); 
    $.ajax({ 
     type: 'DELETE', 
     url: '/article/' + id, 
     success: function (response) { 
      alert('Deleting Article'); 
      window.location.href = '/'; 
     }, 
     error: function (err) { 
      console.log(err); 
     } 
    }); 
}); 
}); 

和我的node.js代碼

app.delete('article/:id', function (req, res) { 
let query = { 
    _id: req.params.id 
}; 
    Article.remove(query, function (err) { 
     if (err) { 
      console.log(err); 
     } 
     res.send('Success'); 
    }); 
}); 

當我按下刪除按鈕返回到我的錯誤404在瀏覽器中沒有發現DELETE http://127.0.0.1:3000/59636fbf6f6c7f1ff40bb1fb 404 (Not Found)

回答

0

在你的Node.js代碼,你根本沒有定義路線host/:id,而是你有/article/edit/:id

而且路由定義 - 在你的Ajax調用你正在做一個如果你想通過執行DELETE對/article/:id的HTTP方法來刪除一篇文章,那麼要確保這條路線添加到您的Node.js文件調出/article/' + id

+0

我複製了錯誤的代碼部分...我編輯了問題 –

+0

您在瀏覽器控制檯中看到了哪些錯誤?在你的終端?你看到你的任何消息是從Node.js和jQuery打印的嗎? – Tamas

+0

當我做刪除時,我也會說做href =「/ delete?id =」或其他的東西而不是href =「#」 – Tamas