You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

INSERT操作后获取insertId显示undefined问题求助

问题原因及解决办法

1. 前端获取insertId的位置错误

后端已经正确返回了包含insertId的result对象,但axios的响应结构中,服务器返回的数据存放在response.data属性里,并非直接挂在response根对象上。修改前端代码如下:

.then(async function (response) {
  console.log(response.data.insertId); // 加上.data获取服务器返回的实际数据
})

2. 修复后端SQL注入风险与字段顺序错误(重要)

你当前用字符串拼接请求参数生成SQL语句,存在严重的SQL注入漏洞,同时原SQL的字段顺序与VALUES参数顺序不匹配,会导致数据插入到错误字段中。改用参数化查询修正:

app.post('/post', (req, res) => {
  const { dcid, dcname, category, ign, item1, q1, item2, q2 } = req.body;
  // 使用?作为占位符,参数数组与字段顺序严格对应
  connection.query(
    'INSERT INTO tradeoffers (DCID, DCNAME, CATEGORY, IGN, ITEM1, Q1, ITEM2, Q2) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
    [dcid, dcname, category, ign, item1, q1, item2, q2],
    (err, result) => {
      if (err) throw err;
      res.send(result);
    }
  );
})

验证步骤

  1. 先修正后端的SQL参数顺序与参数化写法
  2. 修改前端的response.insertId为response.data.insertId
  3. 重新测试,即可正确打印最后插入的ID

内容的提问来源于stack exchange,提问作者janGlin4171

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:41:32