我有三個輸入要獲得三個不同的值。我使用Express.js、node.js、mongodb和ejs模板。
<form action="/save-profile/<%= user. id %>/<%= user.name %>/<%= user.lastname %>/<%= user.description %>" method="POST"/span>>
<div class="input-group mb-3"/span>>
< span class="input-group-text"/span> id="basic-addon1"/span>> Name</span><%= user. username %>
< input type="text" class="form-control" placeholder="'John'" aria-label="用戶名" name="用戶名">
<span class="input-group-text"/span>> lastName</span><%= user. lastname %>
< input type="text" class="form-control" placeholder="" aria-label="Server" name="lastname">
</div>
<div class="input-group">
<span class="input-group-text">/span>描述。 </span>描述: </>
< textarea class="form-control"/span> aria-label="With textarea" placeholder=" name="description"> <%=用戶。 description %></textarea><%=user.
</div>/span>
</p><br>
<button class="btn btn-primary mb-10 btn-lg"/span>> 保存</按鈕>。
</div>/span>
</div>/span>
在js檔案中:
router.post('/save-profile'/span>, async (req, res) => {
const profile_id = await User. findById({ _id: req.body.id })
const updatedName = await User. findOneAndUpdate({ username: req.body.username)
const updatedlastname = await User. findOneAndUpdate({ apellido: req.body.lastname })
const updatedDescription = await User. findOneAndUpdate({ description: req.body.description })
console.log(profile_id,upedName,upedApellido,upedDescription)
res.redirect('/profile') })
我試著用get來做,但沒有成功
。uj5u.com熱心網友回復:
- 首先,
form標簽中的action屬性接受你要處理表單資料的path。你只需要傳遞user.id,對于這個用例,沒有必要傳遞其他欄位。
<form action="/save-profile/<%= user.id %>"/span> method="POST"/span>>
...
</form>
- 其次,在你的路由處理程式中,資料庫記錄可以只使用一個
findOneAndUpdate的呼叫來更新。如果你只打算更新一條記錄,你不需要為每個欄位多次呼叫它。 - 寫在
action屬性中的路徑將顯示為/save-profile/1,例如,在您的路由處理程式中。/save-profile/前面的值,即1可以通過修改路由處理程式中的路徑作為/save-profile/:id來訪問,在回呼中你可以通過req.params.id獲得它。
最后你會得到這個。
router.post('/save-profile/:id'/span>, async (req, res) => {
const response = await User.findOneAndUpdate(
{ _id: req.params.id },
{
username: req.body.username。
apellido: req.body.lastname,
description: req.body.description。
},
{ new: true }.
)
//對回應做一些處理。
res.redirect('/profile'/span>)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/327666.html
標籤:
