MongoDB文档已更新,但axios.put请求无响应且后续代码不执行
问题:React中Axios PUT请求无响应,数据库已更新但前端后续代码不执行
数据库文档已成功更新,但前端axios.put请求无法收到响应,请求后的代码(如console.log(response)、setSentData(body))也未执行,请求似乎一直处于未完成状态。请问是否需要关闭数据库连接或通过其他方式确保请求流程完成?
相关代码
前端React代码
const handleEditFormSubmit = async (editdata) =>{ try{ const id = tabledata[editCategory-1]._id; let body ={} body = {...body, ["Category"]:editdata[`Category${editCategory-1}`]} if (editdata[`Asset${editCategory-1}`] !== undefined){ body = {...body, ["Asset"]:editdata[`Asset${editCategory-1}`],["subCategIndex"]:subCateg.subCategIndex} } const response = await axios.put(`http://localhost:5000/api/assetmaster/update/${id}`, body) console.log(response); setSentData(body); }catch(err){} }
后端Node.js REST API代码
router.put("/update/:id", (req, res)=> { const dbConnect = dbo.getDb(); const listingQuery = { _id: ObjectId(req.params.id) }; const index = req.body.subCategIndex; //Error Handling if null value is recieved let objForUpdate = {}; if(req.body.Category) objForUpdate = {...objForUpdate, ["Category"]:req.body.Category}; if(req.body.Asset) objForUpdate = {...objForUpdate, ["Asset."+ index + ".Name"]:req.body.Asset}; const updates = { $set: objForUpdate }; dbConnect .collection("assetmaster") .updateOne(listingQuery,updates,(err, result)=> { if (err) { res.status(400).send(`Error updating likes on listing with id ${listingQuery.id}!`); } else { console.log("1 document updated"); } }); });
数据库连接文件代码
const {MongoClient} = require('mongodb') const dotenv =require("dotenv"); dotenv.config(); const client = new MongoClient(process.env.ATLAS_URL); let database; module.exports = { connectToServer: (callback) => { client.connect( (err,db) => { if(err || !db ){ return callback(err); } database = db.db("inventory"); console.log("Successfully Connected to MongoDB") return callback(); }); }, getDb: () => { return database; } }
问题原因及解决方案
核心问题
后端在数据库更新成功后没有向客户端返回响应,导致前端的Axios请求一直处于pending状态,无法进入后续代码逻辑。另外,错误处理中存在小bug:listingQuery.id是无效的,因为listingQuery的结构是{_id: ObjectId(...)},应该使用req.params.id。
解决方案
- 后端添加响应返回:在
updateOne的成功回调中,使用res.status(200)返回成功响应,建议用JSON格式便于前端处理。 - 修复错误信息中的ID引用:将
listingQuery.id改为req.params.id。 - 前端完善错误捕获:在catch块中添加错误日志,方便排查问题。
修改后的后端代码
router.put("/update/:id", (req, res)=> { const dbConnect = dbo.getDb(); const listingQuery = { _id: ObjectId(req.params.id) }; const index = req.body.subCategIndex; let objForUpdate = {}; if(req.body.Category) objForUpdate = {...objForUpdate, ["Category"]:req.body.Category}; if(req.body.Asset) objForUpdate = {...objForUpdate, ["Asset."+ index + ".Name"]:req.body.Asset}; const updates = { $set: objForUpdate }; dbConnect .collection("assetmaster") .updateOne(listingQuery, updates, (err, result)=> { if (err) { // 修复ID引用错误,返回结构化错误信息 return res.status(400).json({ error: `Error updating listing with id ${req.params.id}!`, details: err.message }); } else { // 更新成功后返回响应,结束请求 res.status(200).json({ message: "1 document updated", modifiedCount: result.modifiedCount }); console.log("1 document updated"); } }); });
修改后的前端代码(完善错误捕获)
const handleEditFormSubmit = async (editdata) =>{ try{ const id = tabledata[editCategory-1]._id; let body ={} body = {...body, ["Category"]:editdata[`Category${editCategory-1}`]} if (editdata[`Asset${editCategory-1}`] !== undefined){ body = {...body, ["Asset"]:editdata[`Asset${editCategory-1}`],["subCategIndex"]:subCateg.subCategIndex} } const response = await axios.put(`http://localhost:5000/api/assetmaster/update/${id}`, body) console.log(response); setSentData(body); }catch(err){ // 添加错误日志,便于排查问题 console.error("更新请求失败:", err); } }
关于数据库连接的说明
不需要在每次请求后关闭数据库连接。MongoDB的Node.js驱动使用连接池管理连接,MongoClient.connect建立的连接会被复用,频繁关闭/打开连接反而会降低性能。你的数据库连接代码是正确的,保持现有逻辑即可。
内容的提问来源于stack exchange,提问作者New Coder
相关产品推荐
相关产品推荐

