Http works fine in serve but not on android device


#1

Hi,

I am trying to use Http.post, it works well in serve but does not work on the device (android 4.2.2 and 6.0.1).

Here is my code:

console.log('before');
this.http_m.post(
    'http://x.x.x.x/login.php',
    JSON.stringify({ user: "xxx", pass: "xxx" }),
    { headers: this.database_m.defaultHeaders }
).subscribe(
    data_p => console.log("OK"),
    error_p => console.log("error"),
    () => console.log("done")
);
console.log('after');

This code is called when I press a button, here is my output for two press on the button:

0     136028   log      DEVICE READY FIRED AFTER, 1386, ms
1     188760   log      before
2     188778   log      after
0     192738   log      DEVICE READY FIRED AFTER, 1653, ms
1     194985   log      before
2     195007   log      after
0     196672   log      DEVICE READY FIRED AFTER, 743, ms

I don’t have any errors, the application seems to be restarting.
However it works perfectly in serve.

I checked and I do have the following lines in my AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Also in my config.xml:

<allow-navigation href="http://*/*"/>
<allow-navigation href="https://*/*"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<access origin="*"/>

What am I missing?

Thanks.


#2

Honestly not sure if this is still relevant but maybe you need the whitelist plugin? https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/


#3

Thanks, but I already have it installed.


#4

Today I tried in a new empty project and it worked. So it is not an authorization problem and it is not a problem with my request.

The full function is actually like that:

public login(user_p: string, pass_p: string): Observable<void> {
    return new Observable<void>(observer_p => {
        console.log('before');
        this.http_m.post(
            'http://x.x.x.x/login.php',
            JSON.stringify({ user: user_p, pass: pass_p }),
            { headers: this.database_m.defaultHeaders }
        )
        .subscribe(
            data_p => {
                console.log("OK");
                observer_p.next();
                observer_p.complete();
            },
            error_p => {
                console.log("error");
                observer_p.error(ProviderError.LOGIN);
            },
            () => console.log("done")
        );
        console.log('after');
    }
}

I did not think that could be the case but the problem actually comes from the observer_p.next/complete/error being inside the Http.post subscription inside the new Observable.

Am I not allowed to do that?


#5

The crash was actually caused by something else…