我正在使用 CRUD 操作開發博客網站我能夠實作 CRD 操作,但更新 One 存在問題。
問題:-
當我單擊編輯按鈕時,它會打開已成功加載文本檔案的撰寫選項卡,但是當我單擊更新時,它會重定向到主頁但沒有更新,請幫助我擺脫困境。
//This is the code for edit & Update Route
app.get("/posts/:postId/edit", (req, res) => {
Post.findById(req.params.postId, (err, post) => {
if (err) {
console.log(err);
} else {
res.render("edit", { post: post });
}
});
});
app.post("/posts/:postId/edit", (req, res) => {
Post.findByIdAndUpdate(
req.params.postId,
{
$set: {
title: req.body.title,
content: req.body.content,
},
},
(err, update) => {
if (err) {
console.log(err);
} else {
console.log("Post Updated");
res.redirect("/");
}
}
);
});
編輯/更新表格
//This is the Edit ejs file containing the update form
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name="postTitle" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="blog" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
uj5u.com熱心網友回復:
您的錯誤來自 Ejs
您沒有很好地重命名您的 req.body 以匹配您的傳入資料
你本應被使用 title 而不是 postTitle
和內容而不是博客
只需將您的 ejs 編輯為此并測驗 gee
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name=“title" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="content" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
如果這回答了您的問號,則表示已完成
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440575.html
