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

Expo React Native iOS端无法发送网络请求问题求助

问题:Expo React Native iOS开发客户端无法访问本地API(Network request failed)

我用Expo开发React Native应用,已经创建开发客户端并安装在iOS设备上。应用能正常打开进入登录流程,但登录时请求失败,日志如下:

LOG  Sending request to: http://127.0.0.1:5000/api/v1/verify_user.json
ERROR  Network request failed: [TypeError: Network request failed]

已知情况:

  • 接口本身正常,curl请求能返回正确结果:
    curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5000/api/v1/verify_user.json" -d '{"user":{"email":"john@example.com","is_verified":true}}'
    {"success":true}%
    
  • Web端登录功能正常,仅iOS端出现问题。负责移动端登录的函数(来自<ContinueWithEmail.tsx>):
    const verifyUserEmail = async (email: string) => {
      const authEndpoint = 'http://127.0.0.1:5000/api/v1/verify_user.json';
    
      try {
        console.log('Sending request to:', authEndpoint);
        const response = await fetch(authEndpoint, {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: '{"user":{"email":"john@example.com","is_verified":true}}',
        });
    
        console.log('Response status:', response.status);
        const responseData = await response.json();
        console.log('Response data:', responseData);
    
        if (response.ok) {
          if (email && me && Platform.OS !== 'web')
            if (email !== me.email) {
              AsyncStorage.setItem('special_offer', '');
              clearCache && clearCache();
            }
          if (!(!!errors.email && !isValid)) {
            navigation.navigate('continue-with-email-password');
          }
        } else if (responseData.auth_provider) {
          if (Platform.OS === 'web') {
            setShowProviderModal(true);
            setErrorName(responseData.error);
          }
          Alert.alert(
            m('onBoarding.error.title'),
            responseData?.error,
            [
              {
                text: m('onBoarding.error.errorMsg', {
                  provider: responseData.auth_provider,
                }),
                onPress: () => loginPress(),
              },
              {
                text: 'Dismiss',
                onPress: () => {},
              },
            ],
            {
              cancelable: true,
            }
          );
        } else if (responseData.error) {
          setErrors({ email: responseData?.error });
        }
      } catch (error) {
        console.error('Network request failed:', error);
        Alert.alert(
          'Network Error',
          'There was a problem connecting to the server. Please check your internet connection and try again.'
        );
      }
    };
    

我不是移动开发者,不知道怎么调试这个问题,求指导。


解决方案

核心原因

iOS设备上的127.0.0.1指向设备自身,而非你的开发电脑,所以无法访问电脑上运行的本地API服务,这是移动端访问本地服务的常见问题。

解决步骤

  1. 替换为开发电脑的局域网IP

    • 找到开发电脑的局域网IP:
      • Mac:终端执行ifconfig,查看en0下的inet字段值(例如192.168.1.100)
      • Windows:命令提示符执行ipconfig,查看「无线局域网适配器WLAN」下的「IPv4地址」
    • 将代码中的authEndpoint替换为http://你的局域网IP:5000/api/v1/verify_user.json
  2. 确保设备和电脑在同一网络

    • iOS设备必须和开发电脑连接到同一个Wi-Fi网络,否则无法通过局域网IP访问服务。
  3. 检查电脑防火墙设置

    • 确保开发电脑的防火墙允许5000端口的入站请求,避免iOS设备的请求被拦截。
  4. 验证网络连通性

    • 在iOS设备的Safari浏览器中访问http://你的局域网IP:5000/api/v1/verify_user.json,如果能看到接口返回内容,说明网络没问题,问题可能出在App代码逻辑;如果访问失败,继续排查网络配置。

额外优化建议

  • 代码中body硬写字符串不够规范,建议改成动态生成的格式,同时传入用户输入的邮箱:
    body: JSON.stringify({
      user: {
        email: email,
        is_verified: true
      }
    }),
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:27:33