在設定標題后提示我無法設定標題。我的代碼攔截了在 URL 上發送的 put 方法,然后檢查丟失的 id,然后檢查是否沒有未定義輸入的欄位,然后執行 try-catch 方法,在該方法中更新給定的 id。如果 id 不正確,則它會以錯誤回應。我的代碼是:
.put(async function (req, res){
console.log(req.body._id " is id.")
const {_id, issue_title, issue_text, created_by, assigned_to, status_text, open} = req.body;
if(!_id){
res.json({error: "missing _id"})
}
const fields = {issue_title, issue_text, created_by, assigned_to, status_text, open}
const checkAllUndefined = Object.values(fields).every(val => (val == undefined || val == '')? true: false)
if(checkAllUndefined){
res.json({ error: 'no update field(s) sent', _id})
} else{
try{
await db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {$set:
{issue_title,issue_text,created_by, assigned_to, status_text, open,
updated_on: new Date()}}, {
new: true,
omitUndefined: true
})
res.json({ result: 'successfully updated', _id})
}catch(err){
res.json({ error: 'could not update', _id})
}
}
})
uj5u.com熱心網友回復:
如果 _id 未定義,您的第一個 If 陳述句將回傳回應!
if(!_id){
res.json({error: "missing _id"})
}
發送此回應后,您的下一個 if 塊或其 else 塊被執行,這導致發送另一個不可能或不允許的回應!,您必須像這樣嵌套 if else 塊
put(異步函式 (req, res) {
console.log(req.body._id "是 id.")
常量 {_id, issue_title, issue_text, created_by,assign_to, status_text, open} = req.body;
如果(!_id){
res.json({錯誤:“缺少_id”})
} 別的 {
if (checkAllUndefined) {
res.json({error: '未發送更新欄位', _id})
} 別的 {
嘗試 {
等待 db.findOneAndUpdate({_id: new mongodb.ObjectID(_id)}, {
$設定:
{
issue_title,issue_text,created_by,assigned_to,status_text,打開,
更新日期:新日期()
}
}, {
新:真實,
省略未定義:真
})
res.json({result: '成功更新', _id})
} 捕捉(錯誤){
res.json({error: '無法更新', _id})
}
}
}
)
}
通過這樣做,您只發送一次回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481691.html
標籤:表示
