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

NodeJS新PUT API调用异常:预检后主请求挂起求助

问题排查与修复方案

核心问题1:SQL查询参数缺失

你的UPDATE语句里有WHERE id = ?占位符,但conn.query的参数数组只传入了更新对象,没有传递URL中的:id参数,这会导致SQL执行失败,且因为错误处理不完善,请求得不到响应而挂起。

核心问题2:错误处理不完整

  • req.getConnection的连接错误未处理,一旦数据库连接失败,请求会一直挂起
  • 内层try/catch仅打印错误,未向客户端返回错误响应
  • 外层catch为空,完全忽略了文件读取等可能的错误

核心问题3:文件读取未做容错

如果前端未上传文件,req.file会是undefined,fs.readFileSync会直接抛出错误,且没有对应的处理逻辑

修复后的代码

router.put("/carrousel-item/update/:id", fileUpload, (req, res) => {
  // 先处理文件不存在的情况
  if (!req.file) {
    return res.status(400).send({ error: "请上传图片文件" });
  }

  req.getConnection((err, conn) => {
    // 处理数据库连接错误
    if (err) {
      console.error("数据库连接失败:", err);
      return res.status(500).send({ error: "数据库连接失败" });
    }

    try {
      const image = fs.readFileSync(
        path.join(__dirname, "../images/" + req.file.filename)
      );
      const updateData = {
        title_en: req.body.title_en,
        title_es: req.body.title_es,
        sub_title_color_1_en: req.body.sub_title_color_1_en,
        sub_title_color_1_es: req.body.sub_title_color_1_es,
        sub_title_color_2_en: req.body.sub_title_color_2_en,
        sub_title_color_2_es: req.body.sub_title_color_2_es,
        image: image,
      };
      // 传入URL中的id作为第二个参数
      conn.query(
        `UPDATE home_team_section SET ? WHERE id = ?`,
        [updateData, req.params.id],
        (err, rows) => {
          if (err) {
            console.error("SQL执行错误:", err);
            return res.status(500).send({ error: "数据更新失败" });
          }
          res.send({ success: true, data: rows });
        }
      );
    } catch (error) {
      console.error("文件读取或数据处理错误:", error);
      res.status(500).send({ error: "服务器内部错误" });
    }
  });
});

额外检查项

  1. CORS配置:确保cors()中间件是在所有路由之前注册的,比如:
    const cors = require('cors');
    app.use(cors()); // 要在router.use(...)之前调用
    
    如果需要更严格的配置,可以指定允许的方法:
    app.use(cors({
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
    }));
    
  2. 前端请求检查:确认前端发送PUT请求时,正确携带了id参数,且文件上传的格式符合后端fileUpload中间件的要求(比如字段名是否匹配)

内容的提问来源于stack exchange,提问作者Gian Franco Machella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:55:23