Ionic Framework : Android Emulator unable to acces

2019-02-17 00:16发布

问题:

I am trying to implement the Ionic sample tutorial available at http://ccoenraets.github.io/ionic-tutorial/install-ionic.html

I am able to deploy sample app on Android Virtual Device. However the app isn't able to access the REST services hosted on the laptop. I am trying to access the service by changing "localhost" to "10.0.2.2". I have also added the below in the config.xml

<access origin="*"/>

Can someone please let me know how to resolve this issue?

回答1:

If you're using one of the latest versions of cordova you must install the cordova plugin whitelist:

cordova plugin add cordova-plugin-whitelist

if you use the option --save it will add a section to your config.xml file:

cordova plugin add cordova-plugin-whitelist --save

You can read some useful info here about important change in recent cordova updates.

You need to have this:

<access origin="*" />

set in your config.xml file.

If you're using the android emulator you have to change localhost in 10.0.2.2 and, of course, you have to add the port if it is different from the default: 80.

Reference here.

If you're using Genymotion (much better than the android emulator) the ip address is going to be: 10.0.3.2 + the port num.

Samples

Android emulator: http://10.0.2.2:6050/api/checkstatus
Genymotion: http://10.0.3.2:6050/api/checkstatus

If you want to have debug infos for the android emulator run this from the command line:

adb -s emulator-5554 logcat

If you're running you web server in IIS Express chances are your request cannot reach the host. There are a few options here. My favourite solution is to use iisexpress-proxy.
You can install it as an npm package:

npm install -g iisexpress-proxy

and run it specifying the proxy port:

iisexpress-proxy 6050 to 3000

Now you can change your port for your emulators:

Android emulator: http://10.0.2.2:3000/api/checkstatus
Genymotion: http://10.0.3.2:3000/api/checkstatus

Probably the best solution is to use a real android device and debug your app with chrome inspect.

You have to:

  • enable USB debugging on your mobile
  • visit this link in chrome browser (chrome://inspect/#devices)

Once your device show in the list you can hit F12 and see what kind of errors your getting in the browser console.

You can even use the port forwarding forward request to an internal server; basically you can access your hosted services on your laptop through a virtual port you're going to define.