1

I'm building a mobile app in React with Ionic and Capacitor. I'm running a local server with a local API built with Strapi (a headless CMS) that is running on localhost:9000.

I'm having a hell of a time trying to connect my local API to my Ionic app on an Android emulator. The connection works fine on a development server on a web browser. My emulator can also access my local API on a web browser. My app, however, cannot connect to the API when it is running on an emulator.

Here's how I have proceeded so far:

  1. in the .env file of my ionic-react app, I have set the URI to my local API. I have replaced "localhost" with my IP address :

    REACT_APP_API_URL = "http://192.168.1.31:9000"

  2. in the gradle.properties file of my app, I have added proxy settings:

    systemProp.http.proxyHost=192.168.1.31
    systemProp.http.proxyPort=9000
    systemProp.https.proxyHost=192.168.1.31
    systemProp.https.proxyPort=9000
    
  3. in the AndroidManifest.xml file of my app, I have added two permissions:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

Observations:

(✔️) When I run ionic serve to launch a development server in a browser on my local machine, the HTTP requests execute fine. I can fetch my data.

(❌) When I run the app in Android Studio on an emulator, the HTTP requests fail ("Type Error : fetch failed").

(✔️) Yet, when I open a web browser on the aforementioned emulator and try to access my API on 192.168.1.31:9000/api/games, I get a valid response.

The emulator can access my local API, but my app running on the emulator, cannot. It baffles me. Does anyone have an idea what I'm doing wrong?

I have tried replacing my IP address with 10.0.2.2 in the config files, with no success.

From left to right:

  1. my app in a web browser,
  2. my app on an emulator (with an empty carousel because the HTTP request failed),
  3. a web browser on the emulator trying to access the API and getting a valid response.

enter image description here

  • Have you tried configuring clear text traffic? https://stackoverflow.com/a/54268640/3138195 – viv3k Dec 12 '22 at 18:03
  • @viv3k Yes, I've just added it to the manifest and it seems to have solved the problem! Now, for some reason, it won't load Ionic's default placeholder pictures for card components anymore (https://ionicframework.com/docs/img/demos/card-media.png). Maybe because of the HTTPS... ? But at least it can access my API. – Mr_Knightley Dec 12 '22 at 19:27
  • good to know it helped :) Not sure about the placeholder image, but think you should be able to solve it on the debugger. – viv3k Dec 14 '22 at 18:14

0 Answers0