【问题标题】:'DELETE' Request Not Deleting With Jquery and Express'DELETE' 请求不使用 Jquery 和 Express 删除
【发布时间】:2017-01-02 22:50:57
【问题描述】:

我正在使用 node/express 和 jquery 构建一个 api,但我的 DELETE 请求由于某种原因没有触发。

JQUERY:

$('.formula-body').on('click', function (e) {
   if (e.target.className == 'fa-trash-o') {
      $.ajax({
         url: 'formula-api/' + e.target.id,
         type: 'DELETE',
         success: updateIngredient
      });
   }
});

function updateIngredient(data) {
   $('.formula-body').empty();
   var output = '';
   $.each(data, function (key, item) {
      output = `
    <tr>
      <td>${item.name}</td>
      <td>${item.amount}</td>
      <td>${item.notes}</td>
      <td><a><span id ="${key}" class="fa fa-trash-o">  </span></a></td>
    </tr>
    `;
      $('tbody').append(output);
   });
};

HTML:

<div class="centered">
<h2>Your Formula</h2>
  <table class="centered-block pure-table pure-table-striped formula-table">
    <thead class="thead-styled">
      <tr class="centered">
          <th>Ingredient</th>
          <th>Amount</th>
          <th>Notes</th>
          <th></th>
      </tr>
    </thead>
    <tbody class="formula-body">
    </tbody>
  </table>

这是我使用 express 处理 DELETE 请求的路由。

路线:

var app = require('express');
var router = app.Router();
var formulas = require('../data/formula.json');

router.get('/formula-api', function(req, res){
  res.json(formulas);
});

router.post('/formula-api', function(req, res){
  formulas.push(req.body);
  res.json(formulas);
});

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  formulas.push(req.body);
  res.json(formulas);
});

module.exports = router;

POST 和 GET 请求工作正常,但我无法解决问题。控制台不会出现任何错误。

我已将body-parser 实用程序导入app.js,所以这应该不是问题。

基本思想是我有一个表格,每次填写表格时都会附加一个新行。

页面如下所示:

我的想法是,我希望垃圾箱在单击时删除相应的行,但现在它什么也不做。

【问题讨论】:

  • 您是否尝试在您的路线中执行console.log(req.params); 以确保您收到参数?
  • @TaylorAckley - 感谢您的评论,将在早上检查确认。

标签: jquery ajax node.js express


【解决方案1】:

好的,解决了这个问题。我的问题有两个。

1)。当我单击它时,我实际上并没有抓住图标,因为我需要在 jquery 的 $('Grab Element') 语句中包含两个字体很棒的选择器。

2)。在我的路线部分,我有一行说明:

formulas.push(req.body)

这将我的空对象推回到我的 JSON 数组中。

因此,为了纠正这些错误,我进行了以下更改:

更改 1:

if (e.target.className == 'fa-trash-o') {

改为:

if (e.target.className == 'fa fa-trash-o') {

我不知道为什么你不能只使用一个类作为选择器.....我假设它是 Font Awesome 特有的东西。 (如果我错了,很高兴得到纠正)。

更改 2:

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  formulas.push(req.body);
  res.json(formulas);
});

改为:

router.delete('/formula-api/:id', function(req, res) {
  formulas.splice(req.params.id, 1);
  res.json(formulas);
});

这成功了,一切都很顺利。

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 2016-01-12
    • 2019-05-28
    • 2016-05-14
    • 2017-05-24
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    相关资源
    最近更新 更多