我试图在单击按钮时从mongoDB数据库中删除记录。但是,当我在控制台上记录此按钮的值时,它将返回“未定义”
下面是ejs文件
<%- include("partials/header") -%>
<h1>Home</h1>
<!-- A variable for the homepage that is populated by a body of text passed from app.js -->
<p><%= homeText %> </p>
<a class= "btn btn-primary" href="/compose" role="button">Compose a new post</a>
<%# A forEach method with a function holding a parameter of "post" which represents an element in an array, then displaying the element's title and content. %>
<% homeContent.forEach(function(post){ %>
<h1><%= post.title %></h1>
<!-- Displays only the first 100 characters of a post as well as a "read more" hyperlink which directs to a "post" page containing the full content of the post. -->
<p><%= post.content.substring(0, 100) + " ... " %> <a href="/post/<%=post._id %>">Read more</a></p>
<form action = "/delete", method="Post">
<button type="button" class ="btn btn-link" name = "deleteButton" value = "<%=post._id%>" onClick="this.form.submit()" ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg> </button> %>
</form>
<%});%>
<%- include("partials/footer") -%>
这是我试图在我的app.js(服务器文件)中调用我的删除功能的方法
app.post("/delete", function(req,res){
const selectedId = req.body.deleteButton;
Post.findByIdAndRemove(selectedId, function(err){
if(!err){
console.log(selectedId);
res.redirect("/");
}
})
});
当我在控制台上登录ID变量时,很明显它没有正确地从EJS文件访问帖子的ID,因为它返回“ undefined”,因此没有任何内容被删除。有什么明显的我想念的地方吗?我对MongoDB和NodeJS还是很陌生,我一直在寻找一些答案,但似乎无法确定我写的语法上有什么错误。如果您需要更多我的代码,请随时告诉我,谢谢!
提交表单时,仅成功的控件将包含在提交的数据中。
要使<button>
控件成功,它必须是用于提交表单的提交按钮。
您的按钮不是提交按钮(您说过type="button"
),也不(直接)用于提交表单(您正在使用JavaScript)。
因此,您的表单中没有成功的控件,因此POST请求中不包含任何表单数据。
onclick
使用JavaScript提交表单的属性type
按钮停止为提交按钮的属性本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句