Http get fails on device (works in browser)


#1

Started a new ionic app. I fetch json data from a json file hosted on the web. Like http://www.mydomain.ch/abc/data.json . Works well in browser as proxy is defined to redirect localhost to correct url. But in emulator or on device it fails, as it uses the url with localhost, and therefore of course does not find anything. Been searching around for days now… help appreciated.

My setup:

Ionic:
   ionic (Ionic CLI)  : 4.1.1 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.0

Cordova:
   cordova (Cordova CLI) : 8.0.0
   Cordova Platforms     : android 7.0.0, ios 4.5.5
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.2, (and 4 other plugins)

System:
   ios-deploy : 1.9.2
   NodeJS     : v8.11.1 (/usr/local/bin/node)
   npm        : 5.3.0
   OS         : macOS Sierra
   Xcode      : Xcode 9.2 Build version 9C40b

In my config.xml:

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

My provider:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class SbaodataProvider {

  dataurl : any = '/abc/data.json'

  constructor(public http: HttpClient) {
  }

  getRemoteData() {
    return new Promise(resolve => {
      this.http.get(this.dataurl).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
    } 
}

My ionic.config.json

{
  "name": "myApp",
  "integrations": {
    "cordova": {}
  },
  "type": "ionic-angular",
  "proxies": [
    {
      "path":"/abc",
      "proxyUrl": "http://www.mydomain.ch/abc"
    }
  ]
}

Have tried so far without success: removing cordova plugins webview, inappbrowser; using older angular/http instead of angular/common/http; remove proxy entry and set whole path in provider (then it fails in browser, but does still not work on device); emulator iOS as well as Android fails, device so far only on Android tested.

Thanks a lot for hints or working examples of similar approaches. Best regards, Michael


#2

i have the same problem


#3

I’m having the same problem. I get an error when I ionic cordova run android. but it works when I add --livereload. also ionic native http works fine


#4

Hi Peker,
as far as I know with --livereload the app is running on the device like on your desktop after “ionic serve” that is why it works as the proxy setting is getting used instead of looking for localhost.
What do you mean with “works fine” with https://ionicframework.com/docs/native/http/ - then your problem would be solved, isn’t it?
Cheers Michael


#5

Hi JobMichael,
https://ionic.zone/debug/remote-debug-your-app#android
when I look at the logs as shown in this link, I see origin = file://
My problem was from this. When I tried without proxy, android device worked correctly but it does not work in the browser.


#6

Oh, chrome://inspect is really great. Thanks for the link!
As it seems, on the device the request is made to the correct domain but CORS prevents it: “Failed to load http://mydomain.ch/abc/data.json: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access.”
In config.xml I have " <access origin="*" />"
Hmm, I’m lost.


#7

CORS is something you have to set on your server. Depends on what you are using on server side. Google is your friend.


#8

Hi Jacktoolsnet, yeah as it seems I’m not able to avoid this, although a React Native App I built uses fetch to retrieve the same file from the same server and does not get stuck… and Ionic Documentation says CORS will not be an issue on the device but in the browser while testing. But anyway, now looking into what I can do server side as it is my hosted server where the file is coming from.


#9

What are you using on your server? Php nodejs?


#10

Service proxies by Ionic CLI are for testing in the browser mainly, read this: https://ionicframework.com/docs/cli/configuring.html#service-proxies There is also a command that works on devices.


#11

If it’s a CORS problem use HTTP Native, this will automatically fix the CORS problem. You can make some logic to difference if you’re on a browser or device to use either the Native HTTP or Angular’s HttpClient so it won’t be a hell for you to debug.

Or also, you can downgrade from WKWebView to UIWebView, which isn’t really recommended if you’ll release your App for iOS.


#12

nothing really… the file is just lying there in the httpdocs folder - wondering why my react native app is able to fetch it


#13

thanks everybody for the replies, as it is a hobby project I’m not always that quick in responding


#14

Well I never tried to “download” a file with angular.

Seems that you can add course settings in the apache config.


#15

I now resolved my issue this way:

on my host I created a php file which reads my json file and sends the data as a response
on my ionic app I do a http get to the php file and retrieve the data - this works in browser (ionic serve) and on devices (Android & iOS)

my php looks like this:
<?php
$response = file_get_contents("./data.json");
header(‘Access-Control-Allow-Origin: *’);
header(‘Content-Type: application/json’);
echo $response;
?>

my ionic provider ts looks like this:
import { Http } from ‘@angular/http’;
import { Injectable } from ‘@angular/core’;
import ‘rxjs/add/operator/map’;

constructor(public myhttp: Http) { }

fetchRemoteData() {
return new Promise(resolve => {
this.myhttp.get(‘http://domain.com/abc/api.php’)
.map(res => res.json())
.subscribe(data => {
resolve(data.members);
}, err => {
console.log(err);
});
});
}

my “view” controller ts looks like this:
//get Data
fetchData() {
this.provider.fetchRemoteData()
.then(data => {
this.memberdata = data; // the data I’m using to show in the view
this.memberdata.sort((a, b) => a.Name.localeCompare(b.Name));
});
}

Considering that mobile apps might want to show some small amount of remote data, without the overkill of a server / database / rest-api this might be a KISS approach.


#16

hey job,can you tell me how can i solve this issue.i have some cors issue.


#17

add this in your server php file

header(‘Access-Control-Allow-Origin: *’);
header(‘Access-Control-Allow-Headers: Content-Type, x-xsrf-token’);