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

React表单批量提交数组至Node.js/MongoDB API报错排查

React表单提交数组到Node.js/MongoDB API的报错修复

错误1:前端net::ERR_CONNECTION_REFUSED

原因

前端请求的API地址无效,常见情况:

  • API变量配置错误(如缺少端口号、域名/IP不正确)
  • 后端服务未启动,或端口与前端配置不匹配
  • 跨域限制(前后端端口不同时,后端未配置CORS)

修复

  1. 确认后端服务已启动,API变量与后端地址一致(例如后端用5000端口,API应设为http://localhost:5000)
  2. 后端添加CORS配置(若需要):
    const cors = require('cors');
    app.use(cors());
    

错误2:后端TypeError: req.body is not iterable

原因

  1. 前端提交时将数组转为JSON字符串,且Axios请求体包裹为{ fluids: 字符串 },导致后端req.body是对象而非数组
  2. 后端直接尝试展开req.body(对象不可迭代),未正确解析前端传来的数组数据

修复步骤

步骤1:前端取消JSON字符串化

修改React提交函数,直接传递原始数组:

const handleInputFluidsubmit = (event) => {
  event.preventDefault();
  addFluidTopatient(fluids, patientId); // 移除JSON.stringify
};

步骤2:Axios传递正确格式的请求体

调整API函数,确保传递的是数组而非字符串:

const addFluidTopatient = async (fluids, patientId) => {
  dispatch({ type: "ADD_FLUID_LOADING" });
  try {  
    const res = await axios.put(
      `${API}/fluidchart/takenfluid/${patientId}`,
      { fluids: fluids } // 传递数组,而非字符串
    );
    const fluidsData = await res.data; // 避免变量重名冲突
    console.log(fluidsData);
    dispatch({ type: "ADD_FLUID", payload: fluidsData });
  } catch (error) {
    dispatch({ type: "ADD_FLUID_ERROR" });
  }
};

步骤3:后端正确读取数组数据

修改controller,从req.body.fluids获取数组:

const AddDailyFluidchart = async (req, res) => {
  try {
    const newfluid = await patientfluidModel.findOneAndUpdate(
      { patient: req.params.userId },
      {
        $push: {
          fluids: { $each: req.body.fluids }, // 读取请求体中的fluids数组
        },
      },
      { new: true }
    );
    res.status(200).json(newfluid);
  } catch (err) {
    res.status(500).json({ error: err.message }); // 添加错误捕获,便于排查
  }
};

步骤4:确保后端解析JSON请求

确认Express已配置json中间件(需放在路由注册之前):

const express = require('express');
const app = express();
app.use(express.json()); // 解析JSON格式的请求体

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:35:59