Ionic 2 http.get() issue

半城伤御伤魂 提交于 2019-12-06 07:25:39

Response with status:0 for URL: null

That seems to be related to a CORS issue... please check that CORS is enabled in your backend code.

Which way should i use?

http.get() returns an Observable, so one way to use it would be

getResults(){
  this.http.get('http://localhost/api.php')
           .map(res => res.json());
}

And then when you call that method, you need to do it like this:

this.yourService.getResults().subscribe((data) => { console.log(data); });

If you need to return a promise, then you can do it like this:

getResults(){
  this.http.get('http://localhost/api.php')
           .map(res => res.json())
           .toPromise();
}

And use it like this

this.yourService.getResults().then((data) => { console.log(data); });

If you're testing in a browser and hitting CORS issues, ionic has a solution for that You should put something like that in ionic.config and when running ionic serve this will proxy the API for you without CORS.

{
  // ...
  "proxies": [{
    "path": "/api",
    "proxyUrl": "http://xxxxxxxxx"
  }]
}

More info here: http://blog.ionic.io/handling-cors-issues-in-ionic/

It looks like this is a CORS issue. Usually you have to whitelist all domains that are allowed to access your API. But because you are writing an Ionic App, this won't matter once you build your app and run it on your device. That's why I suggest installing a browser plugin that allows you to disable CORS.

Your two code snippets both do the same thing. If you don't want to use observables, I would probably go with the first option:

getResults() {
    return this.http.get('http://localhost/api.php')
                    .toPromise();
}

And then:

this.service.getResults().then(data => {
    // Do something with data
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!