1

I have already enabled cors in my rest API. I can succesfully make a request in my browser, but when i run my application in android studio using this command "ionic cap run android --livereload --external", i cannot get any response from my api. when checking the console i got below error "net: ERR_CONNECTION_REFUSED"

console error

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
luna moonfang
  • 459
  • 1
  • 4
  • 12

2 Answers2

3

If you want to test your app on Android Studio and your API is running on localhost, you need to send requests to 10.0.2.2 instead of localhost. In your case, instead of using the base API URL http://localhost:3000 in your Ionic app, use http://10.0.2.2:3000.

Next, add android:networkSecurityConfig="@xml/network_security_config" to the application element in the AndroidManifest.xml file:

<application
    android:networkSecurityConfig="@xml/network_security_config"

You will need your IPv4 Address. Open Command Prompt, enter ipconfig and take note of the IPv4 Address.

Create a file named network_security_config.xml in the path android\app\src\main\res\xml and replace ipv4address with your IPv4 Address:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
        <domain includeSubdomains="true">ipv4address</domain>
    </domain-config>
</network-security-config>

Finally, run your app with the following command:

ionic cap run android -l --host=0.0.0.0

Source: https://developer.android.com/studio/run/emulator-networking.html

Danilo
  • 31
  • 4
0

You have to set android:usecleartexttraffic attributes in the config.xml.

<platform name="android">
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:networkSecurityConfig="@xml/network_security_config" />
            <application android:usesCleartextTraffic="true" />
        </edit-config>
...
</platform>

Also, you have to add subDomains of RestAPI in network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">127.0.0.1</domain>
    </domain-config>
</network-security-config>