简体   繁体   中英

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

I have been trying to fetch some values from my 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.

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]
- 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
- ... 8 more stack frames from framework internals

The localhost of your emulator or device is not the same as the localhost of your computer. 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.

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.

package.json file:

{
   "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. Google on how you can get the IP address for your system.

Let the IP be: 192.168.xx.xx

2.) Replace -

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.

And that's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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