React Native用Axios调用注册接口,重复用户返回400而非提示如何解决
问题原因
Axios 默认会把所有 HTTP 状态码不在 2xx 范围的请求判定为失败,直接抛出错误。你的当前代码仅编写了请求成功的 .then 处理逻辑,没有捕获错误分支的返回内容,因此 400 响应时你无法拿到后端返回的提示信息。
解决方案
你只需要补全错误捕获逻辑,同时新增状态存储错误提示展示给用户即可,修改代码如下:
- 首先在 state 中新增错误提示字段
constructor() { super(); this.state = { username : "", email : "", password: "", errorMsg: "" // 新增字段存储错误提示 } }
- 修改 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: "请求参数异常,请检查输入内容"}) } }) }
- 在页面渲染区域补充错误提示的展示,比如放在注册按钮上方
{/* 新增错误提示展示 */} {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
相关产品推荐
相关产品推荐

