我試圖更新存盤在 mongodb 中的單個元素(這是一個數字)。這是我發送給資料庫的請求:
const handleDelivered = (num) =>{
const total = service.quantity;
const final = parseInt(total) num;
console.log(total,final);
const url = `http://localhost:5000/services/${idOfService}`;
fetch(url,{
method :'PUT',
headers :{
'content-type': 'application/json',
},
body : JSON.stringify(final)
})
.then(res => res.json())
.then(product =>{
console.log(product);
})
}
存盤在 MongoDB 中的資料是陣列的一個物件。為了執行操作,我嘗試使用 express 構建 API。這是API的代碼
app.put('/services/:id', async(req,res)=>{
const id = req.params.id;
const filter = {_id : ObjectId(id)};
const options = { upsert: true };
const updatedData = req.body;
const updateDoc = {
$set: {
quantity : updatedData.quantity,
},
};
const result = await serviceCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
每當我單擊按鈕進行更新時,它都會顯示一條錯誤訊息:
PUT(link)400 (bad request)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
uj5u.com熱心網友回復:
這應該適合你:
在您的請求正文中執行以下操作:
body : JSON.stringify({quantity: final})
相反,將物件作為字串 whit 發送:
res.send(result);
像這樣以 JSON 格式發送:
res.status(200).json(result);
并讓您的客戶更好地捕捉您的服務拋出的錯誤,將閉包添加catch到獲取中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470069.html
標籤:javascript mongodb 表示
