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

React前端Fetch POST请求异常:Payload存入响应对象名称问题排查

问题根源与解决方案

你的代码核心问题是请求体格式和Content-Type头不匹配,导致后端无法正确解析数据。

场景1:后端API期望JSON格式数据(Postman中使用Raw-JSON调用)

把Content-Type改为application/json,保持请求体为JSON字符串即可:

const handleSubmit = async (e) => {
  e.preventDefault();
  const input = { username: user, email: email, password: pass };
  
  console.log(input);
  try {
    await fetch(`http://localhost:8000/api/register`, {
      method: "POST",
      body: JSON.stringify(input),
      headers: {
        'Content-Type': 'application/json'
      }
    });
    navigate('/login');
  } catch (err) {
    console.log(err.message);
  }
};

场景2:后端API期望表单格式数据(x-www-form-urlencoded)

不能用JSON.stringify,需要把对象转换成表单编码格式的字符串,用URLSearchParams处理最方便:

const handleSubmit = async (e) => {
  e.preventDefault();
  const input = { username: user, email: email, password: pass };
  
  console.log(input);
  try {
    await fetch(`http://localhost:8000/api/register`, {
      method: "POST",
      body: new URLSearchParams(input),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    navigate('/login');
  } catch (err) {
    console.log(err.message);
  }
};

为什么原代码会出错?

你用JSON.stringify生成了JSON格式的请求体,但告诉后端这是x-www-form-urlencoded类型的表单数据。后端解析时会把整个JSON字符串当成一个无键的“值”,最终导致数据被塞进了奇怪的字段里,自然无法正确读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:30:44