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

如何在React中获取Node.js后端POST请求的错误响应

解决React前端获取Node.js后端POST错误响应的问题

问题分析

你当前的代码里,try/catch没法捕获registerUser这个异步Promise的错误——try/catch仅能捕获同步代码异常,Promise的错误需要通过.catch()方法或结合async/await处理。另外还有个细节bug:useState里定义的是Password(首字母大写),但解构时用的是password(小写),这会导致表单密码字段无法正确赋值。

方案1:用Promise的.catch()方法修改registerSubmit

const registerSubmit = (e) => {
  e.preventDefault();
  // 先修复字段名不匹配问题
  const { name, email, Password: password } = user;
  const myForm = new FormData();
  myForm.set("name", name);
  myForm.set("email", email);
  myForm.set("password", password);

  registerUser(myForm)
    .then((res) => {
      toast.success(`${res.data.name}, 注册成功`);
    })
    .catch((error) => {
      // 后端返回的错误信息在error.response.data中
      if (error.response) {
        // 后端返回了错误状态码,直接取返回信息
        toast.error(error.response.data);
        console.log("后端错误信息:", error.response.data);
      } else if (error.request) {
        // 请求已发送但未收到响应
        toast.error("请求失败,请检查网络连接");
      } else {
        // 请求配置阶段出错
        toast.error(`请求错误: ${error.message}`);
      }
    });
};

方案2:用async/await结合try/catch(更直观的异步写法)

const registerSubmit = async (e) => {
  e.preventDefault();
  // 修复字段名不匹配问题
  const { name, email, Password: password } = user;
  const myForm = new FormData();
  myForm.set("name", name);
  myForm.set("email", email);
  myForm.set("password", password);

  try {
    const res = await registerUser(myForm);
    toast.success(`${res.data.name}, 注册成功`);
  } catch (error) {
    if (error.response) {
      // 获取后端返回的错误文本
      toast.error(error.response.data);
      console.log("后端错误信息:", error.response.data);
    } else if (error.request) {
      toast.error("请求超时或网络异常");
    } else {
      toast.error(`请求出错: ${error.message}`);
    }
  }
};

关键补充

  • 后端用res.status(xxx).send(xxx)返回的是纯文本响应,前端直接通过error.response.data就能拿到"Email already exists"或验证错误信息。
  • 建议直接修改useState的字段名,从根源避免解构错误:
const [user, setUser] = useState({
  name: "",
  email: "",
  password: "", // 改成小写p,与解构变量一致
});
const { name, email, password } = user; // 现在解构完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:10:15