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

JS Fetch向Spring后端发送空值问题求助

问题排查与解决方案

根据你描述的情况——状态数据正常但请求payload为空、后端收不到值,从前端代码来看,可能存在以下几个问题,逐一排查:

1. 表单元素name属性不匹配

你的changeHandler通过e.target.name更新对应状态字段,如果表单输入框的name属性和状态里的invname/description/ticker不对应,状态根本不会正确更新。

输入框必须写成这样(确保name和状态key完全一致):

<input 
  name="invname" 
  value={newInvestment.invname} 
  onChange={changeHandler} 
  placeholder="投资名称"
/>
<input 
  name="description" 
  value={newInvestment.description} 
  onChange={changeHandler} 
  placeholder="描述"
/>
<input 
  name="ticker" 
  value={newInvestment.ticker} 
  onChange={changeHandler} 
  placeholder="股票代码"
/>

2. useState更新未使用函数式写法,闭包导致旧值问题

当前changeHandler直接依赖newInvestment的当前值,连续输入时可能因为React状态更新的异步性,导致闭包捕获旧状态值,最终发送请求时数据异常。

修改changeHandler为函数式更新:

const changeHandler = (e) => {
  // 使用prev参数获取最新状态,避免闭包问题
  setNewInvestment(prevState => ({
    ...prevState, 
    [e.target.name]: e.target.value
  }));
};

3. Fetch请求的响应处理错误

你当前的then链中,第一个then只打印了response但未解析数据,第二个then的data会是undefined,这会让你误以为后端返回undefined,实际是前端没解析响应。

同时建议在请求发送前确认数据,拿到响应后再关闭模态框:

const createInvestment = (e) => {
  e.preventDefault();
  
  // 发送前打印确认数据,确保此处输出正确
  console.log("待发送数据:", newInvestment);

  fetch("/api/investments", {
    headers: {
      // 规范写法,首字母大写(不强制但避免潜在解析问题)
      "Content-Type": "application/json",
      Authorization: `Bearer ${jwt}`,
    },
    method: "POST",
    body: JSON.stringify({
      description: newInvestment.description,
      name: newInvestment.invname,
      ticker: newInvestment.ticker,
    })
  })
  .then((response) => {
    // 先判断请求是否成功
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }
    // 解析后端返回的JSON数据
    return response.json();
  })
  .then((data) => {
    console.log("后端返回数据:", data);
    // 拿到响应后再关闭模态框
    props.addInvestment();
  })
  .catch((error) => {
    console.error("请求出错:", error);
  });
};

4. 临时排查:注释关闭模态框的代码

虽然关闭模态框不会阻止请求发送,但如果模态框关闭导致组件卸载,可能引发未知影响。可以先注释掉props.addInvestment(),查看请求payload是否恢复正常。

按照上述步骤排查,大概率能解决payload为空的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:20:46