0

When I post data from my native script angular app which will be running on my android device to my local API which is using dotnet core API. I get an error Error: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 59521): connect failed: ECONNREFUSED. I can hit my API using postman.

I change from using the Httpclient module to HTTP common, with no luck and I have added android:usesCleartextTraffic="true" to the android manifest.

login(user: User) {
    return this.http.post(
      BackendService.baseUrl + "user/login",
      JSON.stringify({
        username: user.email,
        password: user.password
      }),
      { headers: this.getCommonHeaders() }
    )
    .pipe(
      tap((data: any) => {
        BackendService.token = data._kmd.authtoken;
      }),
      catchError(this.handleErrors)
    );
  }

I expect to get an success but I get Error: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 59521): connect failed: ECONNREFUSED.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

2

In order to connect your Android Emulator (or USB-connected Android device) to your dev server, you need to supply the IP-address of the server, since localhost will not point to it from your Emulator/Device.

Tim
  • 212
  • 1
  • 7
  • Hi Tim, I enable my local api to have an ip address and tested the nativescript app and I getting this error. java.io.IOException: Cleartext HTTP traffic to 192.168.1.168 not permitted. I have set the android:usesCleartextTraffic="true" in the manafest – Graeme Hancock Jun 11 '19 at 10:32
  • Depends on your Android API level, but what works for me is Option 1 from https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted – Tim Jun 13 '19 at 11:03
  • I tried option 1 and 2 from https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted and still getting a clearText problem. This it the error I receive : LOG from device Nokia 7 plus: {"originalStack":"Error: java.io.IOException: Cleartext HTTP traffic to 192.168.1.168 not permitted – Graeme Hancock Jun 26 '19 at 06:10
  • Did you run `tns platform clean android` after editing the Android manifest file (or deleting `platforms` altogether)? – Tim Jun 26 '19 at 13:42
  • I tried the clean build still having a problem. It like I can't hit my local API with using nativescript angular app as it has to be https and I can't use self-sign certificate also. – Graeme Hancock Jun 27 '19 at 06:08
  • What prohibits you from using af self-signed certificate? Making your emulator accept it can be a bit of a hassle, but this guide works nicely: https://medium.com/@noumaan/ssl-app-dev-a2923d5113c6 – Tim Jun 27 '19 at 09:43
0

Today I found out you have to use 10.0.2.2 as your endpoint in order to reach the localhost from the emulator.

Question asked about running on the device, yes. But people land here for other keywords too.

Mandolf0
  • 11
  • 1