简体   繁体   English

如何使 localhost rest api 与 react-native 一起使用?

[英]How to make localhost rest api work with react-native?

I have been trying to fetch some values from my spring boot localhost restapi.我一直在尝试从我的 Spring Boot localhost restapi 中获取一些值。 It is throwing a network error.它正在引发网络错误。 I have tried to fetch with Axios.get() too but no result.I have given CORS(origins='*') in my springboot class and method too.我也尝试使用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);
}

[Unhandled promise rejection: TypeError: Network request failed] [未处理的承诺拒绝:TypeError:网络请求失败]
- node_modules\\react-native\\Libraries\\vendor\\core\\whatwg-fetch.js:504:29 in onerror - 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 in dispatchEvent - dispatchEvent 中的 node_modules\\event-target-shim\\lib\\event-target.js:172:43
- ... 8 more stack frames from framework internals - ... 8个来自框架内部的堆栈帧

The localhost of your emulator or device is not the same as the localhost of your computer.localhost的模拟器或设备不一样的localhost您的计算机。 You can map ports between the two, in this case adb reverse tcp:8080 tcp:8080 will map localhost:8080 on your emulator/device to localhost:8080 on your computer.您可以在两者之间映射端口,在这种情况下, adb reverse tcp:8080 tcp:8080将映射localhost:8080的模拟器/设备上localhost:8080您的计算机上。

For people like me who are searching for a solution (add android-dev in scripts), replace the port with your localhost port and rerun the application.对于像我这样正在寻找解决方案的人(在脚本中添加 android-dev),请将端口替换为您的 localhost 端口并重新运行应用程序。

package.json file: 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"
}

The solution that worked for me was :对我有用的解决方案是:

1.) Check your IPv4 address. 1.) 检查您的 IPv4 地址。 Google on how you can get the IP address for your system. Google 了解如何获取系统的 IP 地址。

Let the IP be: 192.168.xx.xx让 IP 为: 192.168.xx.xx

2.) Replace - 2.) 替换 -

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

With -和 -

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

Notice the replacement of localhost with your IP address.请注意将 localhost 替换为您的 IP 地址。

And that's it.就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM