October 22, 2024
Chicago 12, Melborne City, USA
Android

Expo React Native Android Emulator Can't Connect to Express Backend


I’m building a React Native frontend with Expo (managed workflow) and an Express backend running locally. My app works fine on the web version (using expo start --web), but when I test on the Android emulator, the frontend can’t connect to the backend. I’ve tried several things, but nothing seems to work.

What I’ve Tried

  1. Changed the API URL in .env.development:

    • API_URL=http://10.0.2.2:3000 (for Android emulator)
    • API_URL=http://192.xxx.x.x:3000 (my local IP address)
    • API_URL=http://localhost:3000
  2. Updated app.json to allow cleartext traffic:

    "expo": {
      "android": {
        "usesCleartextTraffic": true
      }
    }
    
    
  3. Confirmed backend is running:

    • Accessing http://localhost:3000 in my browser works fine.
      Disabled firewall/antivirus to ensure they aren’t blocking requests.
  4. Tested API URL in Postman using my local IP, and it works.

Relevant code for reference:

.env.development:

#API_URL for web
#API_URL=http://localhost:3000

#API_URL for android
API_URL=http://10.0.2.2:3000

Example frontend api call:

auth.ts:

export const login = async (email: string, password: string) => {
  console.log("API_URL", API_URL);
  const response = await fetch(`${API_URL}/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email, password }),
  });
  const data = await response.json();
  if (!response.ok) {
    throw new Error(data.error);
  }
  return data;
};

I have a basic cors policy that should not effect this I do not think:

// CORS configuration to allow requests from the frontend
const corsOptions = {
  origin: true,
  credentials: true, // Allow credentials (cookies, headers)
};

app.use(cors(corsOptions));

// Handle preflight requests for all routes
app.options('*', cors(corsOptions));

Please let me know if other information is needed.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video