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?
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With