Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using expo client on my android device and have setup up a django server at localhost:8000 and i'm trying to access and endpoint using fetch in react native. I have looked at How can I access my localhost from my Android device? How do you connect localhost in the Android emulator? and How to connect to my http://localhost web server from Android Emulator in Eclipse but that did not work.

I also tried using my machine's ip address instead of localhost, but no results. Here is a sample code

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

What am I doing wrong here?

like image 793
ann Avatar asked Mar 06 '23 09:03

ann


1 Answers

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);
  })
like image 188
csum Avatar answered Mar 10 '23 10:03

csum