嗨,大家好,我最近一直在学习把手,并使用express和mongodb创建一个应用程序,并使用把手作为模板引擎,但在使我的更新和删除按钮正常工作方面存在一个小问题。这是我的代码,我尝试这样做:

//这些是我用来更新和删除我的方法。请求在邮递员中正常运行,但似乎无法弄清楚如何将其连接到我的车把

app.put('/users/:id', (req, res) => {
  const id = req.params.id;
  console.log(id + " was hit")
  const details = { '_id': new ObjectID(id) };
  const user = { name: req.body.name, surname: req.body.surname, cellphone: req.body.cellphone};
  db.collection('users').update(details, user, (err, result) => {
    if (err) {
      res.send({'error':'An error has occurred'});
    } else {
      res.send(user);
    }
  });
});



app.delete('/users/:id', (req, res) => {
  const id = req.params.id;
  const details = { '_id': new ObjectID(id) };
  db.collection('users').remove(details, (err, item) => {
    if (err) {
      res.send({'error':'An error has occurred'});
    } else {
      res.send('User ' + id + ' deleted!');
    }
  });
});


在我的模板中,我有这个:

<div class="col-8">
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Surname</th>
                    <th scope="col">Cellphone</th>
                    <th></th>
                    <th></th>
                </tr>
            </thead>
            {{#each users}}
            <tbody>
                <tr>
                    <td>{{name}}</td>
                    <td>{{surname}}</td>
                    <td>{{cellphone}}</td>
                     <span>
                        <a href="/users/{{_id}}" title="Delete this todo item">Delete</a>
                     </span>
                </tr>
            </tbody>
            {{/each}}
        </table>
    </div>


但是当我按下删除按钮时,这出现了ReferenceError:id未定义错误,并且还尝试将_id更改为我的车把中的id,但是我删除功能并没有到处走。

最佳答案

您正在尝试使用DELETE标记通过链接发出<a> http请求。
您应该注意,由<a>标记创建的html链接使浏览器发出GET http请求。



解决方案1(推荐):

解决此问题的最佳方法是使用axios之类的http客户端库。

这是使用axios的示例:

标记:

<button onclick="deleteToDoItem( {{_id}} )"> Delete </button>


Javascript:

function deleteToDoItem(id) {
    axios.delete("/users/"+id).then(function(response) {
        console.log("Item Deleted");
    })
}




解决方案2:

作为替代解决方案,您可以通过在后端代码中覆盖原始的http请求方法来解决此问题。

检查该项目以获取灵感:https://github.com/expressjs/method-override

这样可以通过将标记更改为以下内容来获得所需的结果:

<a href="/users/{{_id}}?_method=DELETE" title="Delete this todo item">Delete</a>

关于node.js - 蒙戈和 Handlebars ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48043439/

10-10 01:12
查看更多