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

ReactJS报错:Uncaught (in promise) SyntaxError: Unexpected end of JSON input 求解

解决Uncaught (in promise) SyntaxError: Unexpected end of JSON input错误

这个错误的核心原因是:前端用result.json()尝试解析后端返回的内容,但后端返回的不是合法JSON格式,或者根本没返回有效内容。结合你的代码,问题出在这几个地方:

1. 后端没配置JSON请求体解析中间件

你的Node后端用了Express,但没加解析JSON请求的中间件,导致req.body是空对象。前端传的name和email根本没传到后端,存数据时触发Mongoose的必填字段验证错误,进入catch块返回普通字符串,前端用json()解析自然报错。

修复方法:在后端代码最开头加上:

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

2. 后端错误返回的是字符串,不是JSON

你的catch块里用res.send("Something went wrong")返回普通字符串,但前端期望的是JSON。另外,当邮箱重复时(因为email设了unique),user.save()会抛出错误,同样进入这个catch块返回字符串,导致解析失败。

修复方法:把所有res.send()改成返回JSON格式:

// 成功时返回JSON
res.json(req.body);
// catch块里返回错误JSON
res.status(400).json({ error: "Something went wrong", message: e.message });

3. Mongoose连接的then回调写法错误

你写的.then("Database connceted")是错误的,应该传入一个函数来打印连接成功信息:

mongoose
  .connect(url)
  .then(() => console.log("Database connected"))
  .catch((err) => {
    console.log(err);
  });

4. 完善后端的重复邮箱处理

当邮箱重复时,Mongoose会抛出E11000 duplicate key错误,你可以在catch里单独处理这个情况,返回更明确的提示:

catch (e) {
  if (e.code === 11000) {
    return res.status(400).json({ error: "邮箱已被注册" });
  }
  res.status(400).json({ error: "Something went wrong", message: e.message });
}

前端也可以加个错误处理

为了避免前端因为解析失败崩溃,可以给请求流程加try/catch:

const onSubmitHandler = async (e) => {
  e.preventDefault();
  try {
    let response = await fetch("http://localhost:5000/register", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, email }),
    });
    // 先检查响应状态
    if (!response.ok) {
      const errorData = await response.json();
      alert(errorData.error || "请求失败");
      return;
    }
    const result = await response.json();
    console.warn(result);
    alert("Data saved succesfully");
    setName("");
    setEmail("");
  } catch (err) {
    console.error("请求或解析错误:", err);
    alert("数据提交失败,请检查网络或后端服务");
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:31