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

如何修复React Native中Axios调用用户API的Network Error

修复React Native注册功能的Network Error问题

1. 修正API地址格式错误

你的axios请求URL存在格式错误:

await axios.post("http//:192.168.0.103:4000/register", { ...values })

http//:是错误的写法,正确的URL格式应为http://,修改后:

await axios.post("http://192.168.0.103:4000/register", { ...values })

2. 错误处理中重置Formik提交状态

当前handleSignup的catch块未重置Formik的提交状态,导致请求失败后按钮一直处于加载状态,无法再次触发提交,也可能阻塞错误日志输出。修改后的代码:

const handleSignup = async (values, formikActions) => {
  try {
    const {data} = await axios.post("http://192.168.0.103:4000/register", {
      ...values,
    }); 
    console.log(data);
    formikActions.resetForm();
    formikActions.setSubmitting(false);
  } catch (error) {
    console.error("注册请求失败:", error.response?.data || error.message);
    formikActions.setSubmitting(false); // 必须添加此行,重置提交状态
  }
};

3. 补全初始化表单字段

你的initialValue对象缺少repassword字段,但表单中包含该输入框,Formik初始化时会缺失该字段,可能导致表单验证或提交异常。修正初始化值:

const initialValue = {
  name: "",
  email: "",
  password: "",
  repassword: "", // 添加该字段
};

4. 平台网络配置检查

Android

  • 确保android/app/src/main/AndroidManifest.xml已添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 若使用Android 9及以上版本的HTTP请求,需创建android/app/src/main/res/xml/network_security_config.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
    
    并在AndroidManifest.xml的application标签中引用:
    <application
      ...
      android:networkSecurityConfig="@xml/network_security_config">
    

iOS

若使用HTTP请求,需在ios/[你的项目名]/Info.plist中添加ATS例外配置(上线建议改用HTTPS):

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

内容的提问来源于stack exchange,提问作者Rajesh Kumar Jha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:25:32