Bassel
Bassel

Reputation: 452

Making non-secure http requests in Android nativescript

I am trying to make an http request from nativescript to a regular http (not https) server.

    let headers = new Headers();
    headers.append("Content-Type", "application/json");

    this.http.request(
        "http://localhost:3050/register", 
        {
            method: "POST",
            headers: headers,
            body: JSON.stringify({
                username: user.username,
                email: user.email,
                password: user.password
            })
        })

The request worked perfectly when made to an https server, but when made to an http server (which is the server I am currently running), it wouldn't work.

In iOS, I had to add the following in the info.plist file in order to allow the request to the http server, and after that it worked fine:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

However, in Android, the request is still not working, and I cannot find any documentation about changes I need to make in order to get the request working to an http server. The request is not even hitting the server.

Any help is appreciated.

Thanks.

Upvotes: 2

Views: 2145

Answers (2)

nicolas.f.g
nicolas.f.g

Reputation: 1241

I modified the AndroidManifest.xml located in app\App_Resources\Android\src\main from

    <application
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

to

    <application
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

I added the last line: android:usesCleartextTraffic="true"

Then it worked!

See: https://www.nativescript.org/blog/secure-your-mobile-app-securing-data-in-transit

Upvotes: 2

Nick Iliev
Nick Iliev

Reputation: 9670

Localhost means the device you are running on. When using Android your loopback address is no longer the standard 127.0.0.1 (a.k.a. localhost) but something like 10.0.2.2 (it might differ depending on whether you are using AVD or GenyMotion)

More here

You can also use similar solution for cross-platform solution

Upvotes: 3

Related Questions