'android emulator cannot connect localhost dev server
I've an Ionic app that interacts with a server both via REST and sockets.
While I've no issues at all running it via ionic serve and iOS simulator, it seems that on Android emulator I cannot reach a locally running development server.
I've read several posts suggested not to use 127.0.0.1 because it actually serves as loopback for the emulator itself, so I've switched using 10.0.2.2.
Still no luck.
Then I've read that I should do some more extra configurations in the manifest file.
Below is some of the relevant code sections:
<script>
import {isPlatform} from "@ionic/vue";
export const devServerURL = isPlatform('android') ? 'http://10.0.2.2:8008' : 'http://127.0.0.1:8008';
export const prodServerURL = `https://blabla.xyz`;
export const serverURL = process.env.NODE_ENV === 'development' ? devServerURL : prodServerURL;
alert(process.env.NODE_ENV + ' ' + serverURL); // DEBUG PRINT
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'Config',
}
</script>
The above alert is shown as: development http://10.0.2.2:8008 so I know for a fact the app gets the correct settings to start with.
In addition here are the relevant parts of the manifest file:
<application android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config">
...
network_security_config:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
<domain includeSubdomains="true">10.0.2.2</domain>
<domain includeSubdomains="true">192.168.4.104</domain>
</domain-config>
</network-security-config>
Still no luck.
Funny enough, the only workaround I've found working for me was keep using http://127.0.0.1:8008 and right after the emulator is running, run the below command:
adb reverse tcp:8008 tcp:8008
Can anyone point me to the correct approach?
UPDATE:
here's the error I'm getting in logcat:
2022-04-20 17:30:54.842 22224-22224/blabla.xyz E/Capacitor/Console: File: webpack://storyApp/./node_modules/engine.io-client/build/esm/transports/websocket.js? - Line 64 - Msg: WebSocket connection to 'ws://10.0.2.2:8008/ws/socket.io/?EIO=4&transport=websocket' failed: Error in connection establishment: net::ERR_PROXY_CONNECTION_FAILED
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
