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

Expo/React Native扫码API请求报错:parsing failed [TypeError: Network request failed]求助

解决Expo App中Fetch请求"Network request failed"的问题

看起来你遇到的是Expo扫码应用调用本地API时的网络连接问题,我来帮你梳理几个关键排查点:

1. 先修正URL中的转义字符错误

你的代码里拼接URL时用了&,这是HTML的转义字符,在JavaScript直接拼接URL时应该用普通的&,否则会导致URL参数解析错误,服务器可能返回非JSON响应或者直接404,进而触发解析失败的错误。修改后的代码片段:

handleBarCodeScanned = ({ type, data }) => { 
  alert(`Bar code with type ${type} and data ${data} has been scanned! and the phone is ${this.state.maci}`); 
  var BarCodeScannedInApp = `http://你的实际IP:50474/api/ScanPart?PartBarCode=${data}&StationName=${this.state.maci}`; 
  fetch(BarCodeScannedInApp) 
    .then(response => {
      // 先检查响应状态
      console.log('Response Status:', response.status);
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      return response.json();
    })
    .then(result => console.log('API Response:', result))
    .catch(error => console.log('Error Details:', error)) 
};

2. 验证API服务的可达性

  • 确保你的手机和运行API的电脑处于同一局域网(比如连同一个WiFi)
  • 用手机浏览器直接访问API地址,比如:http://你的实际IP:50474/api/ScanPart?PartBarCode=test123&StationName=testStation
    • 如果浏览器打不开,说明API服务本身有问题:
      • 检查API服务是否启动,端口是否正确(50474)
      • 检查服务器防火墙是否开放了50474端口
      • 确保API服务绑定的是0.0.0.0或者本地IP,而不是仅127.0.0.1(否则局域网设备无法访问)

3. 配置API服务器的CORS策略

Expo调试模式下的应用本质是Web容器,会受到跨域资源共享(CORS)限制。如果你的API服务器没有配置允许跨域请求,会导致网络请求失败:

  • 比如ASP.NET Core项目,在Startup.cs中添加CORS配置:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder => builder.AllowAnyOrigin()
                              .AllowAnyMethod()
                              .AllowAnyHeader());
    });
    // 其他服务配置...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其他中间件...
    app.UseCors("AllowAll");
    app.UseRouting();
    // 其他中间件...
}

4. 确认Expo应用的网络权限

虽然Expo默认允许网络请求,但可以在app.json中明确添加Android网络权限,避免权限问题:

{
  "expo": {
    // 现有配置...
    "android": {
      "supportsTablet": true,
      "permissions": ["INTERNET"]
    }
  }
}

5. 调试更详细的错误信息

修改fetch代码,先打印响应状态码和原始响应内容,这样能区分是网络连接失败,还是服务器返回了非JSON响应:

fetch(BarCodeScannedInApp)
  .then(response => {
    console.log('Response Status:', response.status);
    // 先查看原始文本响应,再尝试解析JSON
    return response.text().then(text => {
      console.log('Raw Response:', text);
      try {
        return JSON.parse(text);
      } catch (e) {
        throw new Error(`Failed to parse JSON: ${text}`);
      }
    });
  })
  .then(data => console.log('Parsed Data:', data))
  .catch(error => console.log('Full Error:', error));

按照这些步骤逐一排查,应该能定位到问题所在。

内容的提问来源于stack exchange,提问作者Alex.T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:57:03