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

React中使用Axios获取Express服务器自定义错误响应的方法

解决Axios无法获取Express自定义错误信息的问题

嘿,我来帮你搞定这个问题!其实核心原因是你没找对Axios错误回调里的自定义信息位置,还有后端的错误捕获需要补全,下面一步步说清楚:

问题根源

当Express返回4xx/5xx这类非2xx状态码时,Axios会把请求判定为失败,直接进入.catch()回调。但你现在只打印了err这个Error对象本身——它默认只会显示状态码错误栈,而你后端返回的自定义msg其实藏在err.response.data里,自然拿不到。

另外你的后端代码还有个小疏漏:User.findOne()的catch块只打印了错误,却没给前端返回响应,这会导致前端收到无响应的500错误,同样拿不到明确的错误提示。

具体解决方案

1. 调整前端Axios的错误处理逻辑

在.catch()里,要通过err.response.data获取后端的自定义错误信息,同时还要处理网络异常(比如服务器宕机、没联网这类没有response的情况):

handleSubmit = e => { 
  e.preventDefault(); 
  const { email, password } = this.state; 
  axios 
    .post("/api/users/login", { email, password }) 
    .then(res => console.log(res.data.msg, res.status)) 
    .catch(err => {
      // 分情况处理错误
      if (err.response) {
        // 服务器正常返回了响应,直接取自定义错误信息
        console.log(err.response.data.msg);
      } else {
        // 网络层面的错误(比如服务器没启动、断网)
        console.log("网络异常,请检查服务器状态");
      }
    }); 
};

2. 补全后端的错误响应

给User.findOne()和bcrypt.compare()的catch块都加上响应返回,确保前端无论哪种错误都能拿到明确提示:

router.post("/login", (req, res) => { 
  const { email, password } = req.body; 
  User.findOne({ email }) 
    .then(user => { 
      if (!user) return res.status(400).json({ msg: "No such user in the DB" }); 
      
      bcrypt.compare(password, user.password)
        .then(isMatch => { 
          if (!isMatch) { 
            return res.status(400).json({ msg: "Wrong password" }); 
          } 
          req.session.userId = user.id; 
          res.status(200).json({ msg: "You have logged in" }); 
        })
        // 捕获密码比对时的错误
        .catch(err => {
          console.log("密码比对出错:", err);
          res.status(500).json({ msg: "服务器验证密码时出错" });
        }); 
    }) 
    // 捕获用户查询时的错误
    .catch(err => {
      console.log("查询用户出错:", err);
      res.status(500).json({ msg: "服务器查询用户时出错" });
    }); 
});

验证效果

现在再测试错误场景:

  • 用户不存在时,前端会打印"No such user in the DB"
  • 密码错误时,会打印"Wrong password"
  • 服务器内部出错时,也会收到对应的500级错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:03:12