【问题标题】:Mongo and handlebarsMongo 和车把
【发布时间】:2018-01-01 01:43:18
【问题描述】:

大家好,最近我一直在学习把手,并使用 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 is not defined 错误,并且还尝试在我的车把中将 _id 更改为 id,但我的删除功能不会去任何地方。

【问题讨论】:

  • a 标记发出 GET 请求,而不是 DELETE 请求。因此,当您单击该按钮时,app.delete 处理程序不会处理它。您需要使用 javascript 向该端点发送 DELETE 请求。
  • 谢谢,在您发布的有用评论之后,我最终为应对挑战做了什么我实际上更改了调用以使其成为帖子而不是删除,并且在 html 中我将其从删除更改为post plus l 停止使用 href 而是在我的车把中使用它
    在我提出更好的解决方案之前,它是临时修复。非常感谢您的帮助,非常感谢它

标签: node.js mongodb express


【解决方案1】:

您正在尝试使用&lt;a&gt; 标记发出带有链接的DELETE http 请求。 您应该注意由&lt;a&gt; 标签创建的html 链接,使浏览器发出GET http 请求。


解决方案 #1(推荐):

解决此问题的最佳方法是使用 http 客户端库,例如 axios

这是一个使用 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>

【讨论】:

    猜你喜欢
    • 2016-07-31
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多