【发布时间】: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 而是在我的车把中使用它
在我提出更好的解决方案之前,它是临时修复。非常感谢您的帮助,非常感谢它