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

React Native用Axios调用注册接口,重复用户返回400而非提示如何解决

问题原因

Axios 默认会把所有 HTTP 状态码不在 2xx 范围的请求判定为失败,直接抛出错误。你的当前代码仅编写了请求成功的 .then 处理逻辑,没有捕获错误分支的返回内容,因此 400 响应时你无法拿到后端返回的提示信息。

解决方案

你只需要补全错误捕获逻辑,同时新增状态存储错误提示展示给用户即可,修改代码如下:

  1. 首先在 state 中新增错误提示字段
constructor() {
    super();
    this.state = {
        username : "",
        email : "",
        password: "",
        errorMsg: "" // 新增字段存储错误提示
    }
}
  1. 修改 submit 方法中的 Axios 请求逻辑,补充错误捕获
submit = () => {
    console.log(this.state.email);
    console.log(this.state.username);
    console.log(this.state.password);

    axios
    .post(`http://localhost:8080/api/auth/signup`, {
        username: this.state.username,
        email: this.state.email,
        password: this.state.password,
    })
    .then((response) => {
        console.log(response.data);
        // 注册成功逻辑,可自行补充页面跳转等操作
        this.setState({errorMsg: ""}) // 成功清空错误提示
    })
    .catch((error) => {
        // 处理错误响应
        if(error.response) {
            // 后端已返回响应,状态码非2xx
            // error.response.data 就是你要的后端返回的提示内容
            this.setState({errorMsg: error.response.data})
        } else if(error.request) {
            // 请求已发出但未收到响应,一般是网络问题
            this.setState({errorMsg: "网络异常,请检查网络连接后重试"})
        } else {
            // 请求配置错误
            this.setState({errorMsg: "请求参数异常,请检查输入内容"})
        }
    })
}
  1. 在页面渲染区域补充错误提示的展示,比如放在注册按钮上方
{/* 新增错误提示展示 */}
{this.state.errorMsg ? <Text style={{color: 'red', marginBottom: 10}}>{this.state.errorMsg}</Text> : null}
<Button title="Register" onPress={()=> this.submit()}/>

补充说明:如果你后续改用真机调试,需要把接口地址里的 localhost 替换为你电脑的局域网IP,否则会出现无法连接后端的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:07