How do I get my localhost to work for my android emulator?

I am using a Django server, and a react native frontend (with expo).

I can access the server fine on my browser and with the iOS simulator (I use a Mac), however, on the android simulator, I get a network error, and it can’t connect to my server.

Here is the react native code that works fine:

  componentDidMount = () => {
    fetch("http://127.0.0.1:8000/api/events/?featured=true", {
      method: "GET",
    })

What am I doing wrong?

Answer

  1. I added my machine’s IP to ALLOWED_HOSTS in my Django settings.py
  2. Then I ran my server on my machine’s IP with the command: ./manage.py runserver XX.XXX.XX.XX:8000 (replace the X’s with your machine’s IP)
  3. And then I changed all my react native functions to the following:
const root = "XX.XXX.XX.XX"
  componentDidMount = () => {
    fetch(root+"api/events/?featured=true", {
      method: "GET",
    })

Replace the X’s in the above code with your machine’s IP-address.