React Native Android Fetch Failing on Connection to Local API

React-Native - can't fetch from connected Android device to localhost endpoint

First try this
- For android: run the following command in terminal and try again

adb reverse tcp:8081 tcp:8081

If it doesn't work try this

  • Shake device(android)

  • Select dev settings and click "Debug server host & port for device"

  • Under debugging type local ip address and port number. (Ex: http://127.0.0.1:8080)

React native fetch api does not work with localhost, IP, or even 10.0.2.2

This may be an issue with the django configuration. Especially if your phone's web browser is unable to get the expected response as well.

From the Django docs:

Note that the default IP address, 127.0.0.1, is not accessible from other machines
on your network. To make your development server viewable to other machines on the
network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0 or :: (with IPv6 enabled).

See How to access the local Django webserver from outside world, though the answer also applies on a local network:

python manage.py runserver 0.0.0.0:8000

You can replace 0.0.0.0 with the machine's address if you know it.


Also worth noting in your response handler that response.json() returns a Promise, not JSON. Instead you want:

fetch('http://my-ip-address:8000/restapi/')
.then(response => response.json())
.then(responseJson => {
console.log("success");
console.log(responseJson);
})
.catch(error => {
console.error(error);
})


Related Topics



Leave a reply



Submit