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

iOS端Expo Go应用Axios API请求出现网络故障问题排查

Expo Go iPhone端Axios自定义Service部分接口报Network Error问题排查与解决

问题现象

使用Expo Go在iPhone上运行React Native应用,后端部署在Render平台:

  • 自定义ApiService类统一处理请求时,部分接口返回[AxiosError: Network Error],且请求未到达后端
  • 相同接口在Postman、Expo web端直接调用axios.get时可正常访问
  • 一周前功能正常,已尝试添加appTransportSecurity配置、重装依赖,问题未解决

排查与解决步骤

1. 检查URL拼接逻辑(最可能的原因)

自定义ApiService中baseURL与请求路径的拼接可能存在格式问题:

  • 如果process.env.API_URL末尾没有斜杠(如https://your-render-domain.com/api),调用apiService.call('get', 'student/xxx')会拼接成https://your-render-domain.com/apistudent/xxx,导致路径错误
  • 而直接拼接process.env.API_URL + 'student/xxx'时,你可能手动补了斜杠,所以路径正确

修复方法:
修改ApiService构造函数,确保baseURL末尾始终带斜杠:

constructor() {
    const rawUrl = process.env.API_URL;
    this.baseUrl = rawUrl.endsWith('/') ? rawUrl : `${rawUrl}/`;
    this.axios = axios.create({
        baseURL: this.baseUrl,
    });
}

2. 修正Axios请求参数传递逻辑

Axios中GET请求的参数应放在params字段,而非data字段。虽然你的报错请求未传参数,但统一处理逻辑可能隐含问题:
修复方法:
调整call方法,根据请求方法区分参数传递方式:

async call(method, url, paramsOrData) {
    const headers = {
        "Content-Type": "application/json",
    };
    const config = { method, url, headers };
    
    // GET请求用params,其他方法用data
    if (method.toLowerCase() === 'get') {
        config.params = paramsOrData;
    } else {
        config.data = paramsOrData;
    }

    try {
        const response = await this.axios(config);
        return response.data;
    } catch (err) {
        return err;
    }
}

3. 对齐Axios实例与直接调用的配置

直接调用axios.get时的配置可能与自定义实例存在差异,可将成功配置同步到实例中:
修复方法:
在创建Axios实例时直接设置默认headers,避免call方法中重复传递导致冲突:

constructor() {
    const rawUrl = process.env.API_URL;
    this.baseUrl = rawUrl.endsWith('/') ? rawUrl : `${rawUrl}/`;
    this.axios = axios.create({
        baseURL: this.baseUrl,
        headers: {
            "Content-Type": "application/json",
        }
    });
}

4. 排除Expo Tunnel代理问题

使用--tunnel模式时,Expo依赖ngrok代理,可能存在路径解析异常:

  • 尝试切换到--lan模式(确保iPhone与开发机同一局域网)启动项目:
npx expo start --lan
  • 如果问题消失,说明隧道代理存在异常,可重启Expo服务或更换网络环境尝试

5. 验证环境变量正确性

确认自定义ApiService中process.env.API_URL的取值与直接调用时一致:

  • 在ApiService构造函数中添加日志:
constructor() {
    this.baseUrl = process.env.API_URL;
    console.log('ApiService Base URL:', this.baseUrl); // 在Expo调试控制台查看输出
    this.axios = axios.create({
        baseURL: this.baseUrl,
    });
}
  • 若输出为空或错误,检查react-native-dotenv的Babel配置是否正确,确保环境变量正常加载

6. 检查Axios版本兼容性

当前使用的axios@1.6.8可能与Expo 50存在兼容性问题,尝试降级到稳定版本:

npm install axios@1.6.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:07:47