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

React Native请求本地Symfony API时出现response.json未定义错误

解决React Native请求本地Symfony API的TypeError问题

1. 先修复代码链式调用的直接错误

你代码里的第一个.then()块没有返回response,导致后续response.json()调用时response是undefined,这就是报错的核心原因。同时注意你的Symfony API返回的是直接数组,不是带hardwarePlacements字段的对象,也要修正状态赋值逻辑:

componentDidMount() {
  return fetch('http://10.161.170.86:8000/api/hardwarePlacement')
  .then((response) => {
    console.log(response.ok);
    // 必须返回response,让下一个then能接收
    return response;
  })
  .then((response) => response.json())
  .then((responseJson) => {
    console.log(responseJson);
    this.setState({
      isLoading: false,
      // API返回的是直接数组,无需取hardwarePlacements字段
      dataSource: responseJson,
    })
  })
  .catch((error) => {
    console.log(error)
  });
}

2. 解决本地API的网络访问问题

公网请求正常但本地失败,主要是CORS配置或网络可达性问题,按以下步骤排查:

(1)配置Symfony的CORS支持

本地React Native和Symfony属于不同源,必须开启CORS允许跨域请求:

  • 安装CORS扩展:
composer require nelmio/cors-bundle
  • 在config/packages/nelmio_cors.yaml添加配置(开发环境可宽松配置):
nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['*']
        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
        allow_headers: ['*']
        max_age: 3600
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_methods: ['GET', 'OPTIONS']
            allow_headers: ['Content-Type']
  • 重启Symfony服务器。

(2)确保网络可达性

  • 确认运行Symfony的电脑和React Native测试设备(模拟器/真机)在同一WiFi局域网内
  • 启动Symfony时监听全部网卡,避免仅本地可访问:
symfony server:start --port=8000 --allow-http --address=0.0.0.0

(3)平台额外配置

  • iOS模拟器:允许HTTP请求,在Info.plist中添加:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
  • Android:确保AndroidManifest.xml包含网络权限:
<uses-permission android:name="android.permission.INTERNET" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:15:34