如何在前端JavaScript中获取并使用SQL返回的插入ID?
解决前端获取插入记录ID的问题
首先,你当前的前端代码未接收axios.post的返回值,后端已正确返回插入的ID数组,只需在前端接收并提取即可。
步骤1:修改前端代码接收返回值
将await axios.post(...)改为接收响应对象,从中提取插入的ID:
const addNewMainTypes = async () => { try { // 接收axios返回的响应对象 const response = await axios.post(`${serverBaseUrl}/insertRowtoMain`, { nodeid: newMaintenance.nodeid, maintenancetype: newMaintenance.maintenancetype, personnel: newMaintenance.personnel, process: newMaintenance.process, date: newMaintenance.date, }); // 后端返回的是包含插入记录的数组,提取第一个元素的id字段 const insertedId = response.data[0].id; console.log("插入的记录ID:", insertedId); // 此处可直接使用insertedId执行后续业务逻辑 } catch (err) { throw err; } // 原有列表刷新逻辑保持不变 const maintenance = await getMain(); setMaintenance(maintenance); const maintenanceList = await getMainTypes(); setMaintenanceList(maintenanceList); };
步骤2:(关键)修复后端SQL注入漏洞
你当前的SQL字符串拼接方式存在严重的SQL注入风险,必须改用参数化查询:
app.post("/insertRowtoMain", (req, res) => { const { nodeid, maintenancetype, personnel, process, date } = req.body; // 使用参数占位符$1-$5,对应后续数组中的参数顺序 let insertQuery = `insert into maintenance(nodeid,maintenancetype, personnel, process, date) values($1, $2, $3, $4, $5) returning id`; pool.query(insertQuery, [nodeid, maintenancetype, personnel, process, date], (err, result) => { if (!err) { console.log("insertRowtoMain", result.rows); res.status(200).json(result.rows); // 统一用JSON格式返回,和错误响应保持一致 } else { res.status(400).json({ message: err.message }); // 错误状态码改用400(请求错误)更符合HTTP语义 console.log("insertRowtoMain error", err.message); } }); });
补充说明:
- 参数化查询会自动处理字符串转义,彻底杜绝SQL注入攻击。
- 后端错误响应状态码从404改为400,因为该场景属于请求参数或SQL执行错误,而非资源不存在。
- 统一使用
res.json()返回数据,确保前后端数据格式一致。
内容的提问来源于stack exchange,提问作者apotamkinn
相关产品推荐
相关产品推荐

