Reputation: 622
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?
Upvotes: 4
Views: 8874
Reputation: 152
In addition to csum's answer, please check if the firewall has allowed remote access to your android device (device IP as remote) for the django server. If you've any anti-virus installed and controlling firewall, ensure that it has a rule in its firewall.
Upvotes: 1
Reputation: 2002
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);
})
Upvotes: 9
Reputation: 4879
Acording to your code,
:8080
:8000
Check again. And I recommend using PostMan when you test your server apis.
Upvotes: 0