16

We're trying to connect to an API (.net core 2.2) from react-native (version 0.59), via localhost, both apparently running on the same IP, different ports, react-native on port 8080, and the API on the 44344, the issue happens the moment we fetch the URL from react-native

We’ve also tested running the URL from Postman and everything seems ok, also from any of the web browser installed (safari/chrome), even we tested the browser INSIDE react-native iOS, and it works.

Any API running outside localhost works perfectly, is the localhost were we failed.

Network request failed.

onerror
    whatwg-fetch.js:504:29
dispatchEvent
    event-target.js:172:43
setReadyState
    XMLHttpRequest.js:580:29
__didCompleteResponse
    XMLHttpRequest.js:394:25
emit
    EventEmitter.js:190:12
__callFunction
    MessageQueue.js:366:47
<unknown>
    MessageQueue.js:106:26
__guard
    MessageQueue.js:314:10
callFunctionReturnFlushedQueue
    MessageQueue.js:105:17
callFunctionReturnFlushedQueue
    [native code]:0

Part of the code (function) that fetch the API, very simple (for now)

async Submit(){
  //GET METHOD
  try {
        let response = await fetch('https://192.168.1.56:44344/api/values');
        let responseJson = await response.json();
        return Alert.alert(JSON.stringify(responseJson));
  } catch (error) {
        console.error(error);
  }
}

Ok first of all, we've tried EVERY possible solution, to connect my react native app to my .net core API rest, both running in localhost, this is the list so far, of the things that we've tried so far, and still no result.

  • Localhost
  • 127.0.0.1
  • Computer IP (network IP not MAC address)
  • React Native blank project (from the ground up)
  • API .net core blank project (from the ground up)
  • Running snack expo + API .net core
  • IP forwarding (We can't do that do to our job policies/Not the solution we're looking for)
  • http/https
  • Different ports
  • Android and iOS permissions from react-native
  • Same network different IP (this sorta worked, but we don't know exactly why it doesn't work running both react-native and the API in the same IP (localhost))
  • 10.0.2.2 (for android)
  • Enable CORS on API .net core (but apparently this doesn't work on native apps, only for web)
  • Expose the ip through ngrok/serveo (We can't do that do to our job policies/Not the solution we're looking for)
  • Frisbee
  • Axios
  • Websocket (We can't do that do to our job policies/Not the solution we're looking for)
  • XMLHttpRequest (status code error 0)
  • Firewall/proxy (our network is free from firewalls and proxies)
  • Web browser plugins (deactivated and/or uninstalled)
  • Cache/cookies
  • Docker (We can't do that do to our job policies/Not the solution we're looking for)
  • Reboot my Macbook Pro

We expect react native to fetch the API, so we can continue with the office 365 login authentication.

EDIT: I just discovered that fetching the machine IP (this time running windows), with my IP being 192.168.0.9 both on the API and the react native, the fetch result showed me the 10.0.2.2:80 in the header of the JSON response. I suppose it is the "localhost" IP from react native. How am I supposed to fetch an IP from localhost if react native is not letting me to do so?

EDIT: We had to go for plan B this time around, we've made it work with a docker on the API, but I need a solution for this problem. I'm 99% sure the issue is react-native and nothing else.


EDIT: After all these weeks one of my colleges managed to solve it. First of all, we couldn't make the firewall in my Macbook Pro work properly. Second, we solved that and found out our API was having issues. He found out the redirection was on https, and the certifications weren't working properly, so he changed this
"applicationUrl": "http://192.168.0.114:5001;https:192.168.0.114:5001"

to

"applicationUrl": "http://192.168.0.114:5001"
8
  • Did you leave the port you use open in the firewall? Commented Jul 19, 2019 at 3:21
  • i just checked and the firewall is deactivated, so i suppose it should be working on every port Commented Jul 19, 2019 at 13:32
  • Could you try 192.168.1.56:80 ? Commented Jul 19, 2019 at 14:21
  • nope, didn't worked, change on react, and then on the api, neither work Commented Jul 19, 2019 at 14:36
  • the port 80 on the api gives me an socket error, i'm assuming that port is being used Commented Jul 19, 2019 at 14:46

7 Answers 7

14

I got the same issue while fetching localhost API from react-native. Here is what I did to solve this issue. In the startups class, I removed //app.UseHttpsRedirection(); from Configure method.(Not sure if it is needed)

After that in the launchsetting.js file under the properties folder, I changed from

"applicationUrl": "https://localhost:5001;http://localhost:5000"

to "applicationUrl": "http://localhost:5000"

and in the React native part, I simply changed my localhost with my IP:

fetch('http://localhost:5000/values/') to fetch('http://127.0.0.1:5000/values/')

This completely worked for me

Sign up to request clarification or add additional context in comments.

1 Comment

In my case, I got it to work on the android emulator using the IP: 10.0.2.2 instead of localhost. Otherwise, good answer.
4

Take command prompt and type ipconfig, so we will be getting many addresses. From that take IPV4 and copy it to the clipboard. Then paste this address to both the back ends port address and front end port address. eg say IPV4 address is 192.168.1.3 then make you your back end route API similar to this http://192.168.1.3:8080/patients, where 8080 is the port number (never mind). And use the same for the front end to grab the API result.

Comments

0

You have to do two things.

1 - Use http://192.168.1.x:8080 (your local ip ) rather than http:// localhost:8080 in your client.

2 - Add following code snippets to your .net core web api project in Startup.cs.

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

services.AddCors(options =>
        {

            options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://192.168.1.x:8080")
                              .AllowAnyHeader()
                              .AllowAnyMethod();
                          });

        });

.
.
.
app.UseCors(MyAllowSpecificOrigins);

Comments

0

Something that worked for me was run adb reverse tcp:<YOUR PORT> tcp:<YOUR PORT> in terminal

I'm not sure of how it works exactely, but I guess it makes some sort of mapping from the virtual device port to your machine's.

Example:

adb reverse tcp:8080 tcp:8080

Comments

0

Using the local IP address worked for me, with no additional configuration.

Example:

 fetch("http://192.168.0.103:4000/books", {
      method: "GET"
    })

Comments

0

Thanks for all the insight, but none of the above solutions worked for me.

What did work:

https://ngrok.com/ - Download ngrok, signup, and connect your account. ngrok creates a private https localhost tunnel.

Setup - https://dashboard.ngrok.com/get-started/setup

Unzip to install:

unzip /path/to/ngrok.zip

Connect your ngrok account (Non functioning example auth token):

ngrok config add-authtoken 2ySPR5UeS3Fjf5YAblNRe7ZcV1o_9sdf2SDFGHjEQaOCE6xEi

Use the command (with your desired port number):

ngrok http 8080

Once ngrok is online, replace your localhost address:

http://localhost:8080 
http://127.0.0.1:8080
http://192.168.0.100:8080

with the forwarding web address (Non functioning example address):

https://ebda-61-137-45-130.ngrok.io

I've used ngrok countless times for testing on a variety of networks without issue. So far its the only foolproof method I've found for testing localhost APIs.

Comments

0

1 . First I hosted my api on IIS locally . ( If you having trouble doing it please refer to this tutorial : https://www.youtube.com/watch?v=Lt3wve_nb0g )

2 . Then I commented //app.UseHttpsRedirection();. This line using http redirection on my API's program.cs .

3 . Use your IP address instead of localhost Instead of this http://localhost:xxxx/API/, use http://197.xxx.xx.x: xxxx

Hope these will work for you guys .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.