Ionic 2 run android http rest API call not working

Ionic 2 http call not working on android device while it working on browser. I also add cordova-whitelist-plugin and content security policy. Can you please solve this issue.

Here is my code:

 <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

config.xml

  <access origin="*"/>
**home.ts** import { Component } from '@angular/core'; import { Http } from '@angular/http'; import { NavController } from 'ionic-angular'; import 'rxjs/add/operator/map';

@Component({
selector: ‘page-page1’,
templateUrl: ‘page1.html’
})
export class Page1 {

apiData: any;

constructor(public navCtrl: NavController, public http: Http) {
this.getApiData();
}

getApiData() {
var response = this.http.get(‘http://192.168.56.1:4000/api/type’)
.map(res => res.json())
.subscribe(
data => {
this.apiData = data;
alert(JSON.stringify(this.apiData));
}, err => {
alert(err);
}
);
return response;
}

}

1 Like

It worked for me, when I tried the following…

In Config.xml, allow access & navigations to your domains:

<access origin="http://yourdomain1.com" />
<allow-navigation href="http://yourdomain1.com" />

Then in index.html, add the Content-Security-Policy as below:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' http://yourdomain1.com  data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline';  media-src *;  script-src 'self' 'unsafe-eval' 'unsafe-inline';">

If I write the CSP in the index.html and then i run the app in device mode like this:

ionic cordova run android --device

Then, the line of the index.html is removed.

How can i do this?

This phrase is ambiguous. Based on the rest of your post, I suspect you are editing the index.html under www. Don’t touch anything in that directory. If you have a C background, that’s the object code directory. Only edit things under src.