【问题标题】:How to make localhost rest api work with react-native?如何使 localhost rest api 与 react-native 一起工作?
【发布时间】:2019-08-19 16:19:57
【问题描述】:

我一直在尝试从我的 spring boot localhost restapi 中获取一些值。它正在引发网络错误。我也尝试使用Axios.get() 获取但没有结果。我也在我的springboot 类和方法中给出了CORS(origins='*')。

async componentDidMount()
{

  const response = await fetch('http://localhost:8080/jobSeeker/allJobSeekers');  

   const body = await response.json();   

   this.setState({ users: body, isLoading: false });

   console.log(users);
}

[未处理的承诺拒绝:TypeError:网络请求失败]
- node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:29 in onerror
- 调度事件中的 node_modules\event-target-shim\lib\event-target.js:172:43
- ... 来自框架内部的另外 8 个堆栈帧

【问题讨论】:

    标签: java rest spring-boot react-native


    【解决方案1】:

    您的模拟器或设备的localhost 与您计算机的localhost 不同。您可以在两者之间映射端口,在这种情况下,adb reverse tcp:8080 tcp:8080 会将您的模拟器/设备上的localhost:8080 映射到您计算机上的localhost:8080

    【讨论】:

    • 非常感谢兄弟!!像魅力一样工作。这是我在 StackOverflow 上的第一个问题。你节省了我的时间。非常感谢!!!
    • @Lokeshch 如果这回答了您的问题,请选择它作为答案。
    【解决方案2】:

    对于像我这样正在寻找解决方案的人(在脚本中添加 android-dev),请将端口替换为您的 localhost 端口并重新运行应用程序。

    package.json文件:

    {
       "main": "node_modules/expo/AppEntry.js",
       "proxy": "http://localhost:8080",
       "scripts": {
       "start": "expo start",
       "android": "expo start --android",
       "ios": "expo start --ios",
       "web": "expo start --web",
       "eject": "expo eject",
       "android-dev": "adb reverse tcp:8080 tcp:8080 && react-native run- android"
    }
    

    【讨论】:

      【解决方案3】:

      对我有用的解决方案是:

      1.) 检查您的 IPv4 地址。谷歌了解如何获取系统的 IP 地址。

      设IP为:192.168.xx.xx

      2.) 替换 -

      const response = await fetch('http://localhost:8080/jobSeeker/allJobSeekers');
      

      与 -

      const response = await fetch('http://192.168.xx.xx:8080/jobSeeker/allJobSeekers');
      

      注意 localhost 替换为您的 IP 地址。

      就是这样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-15
        • 1970-01-01
        • 2019-05-04
        • 2017-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多