问题
I tried to make a http.get() call with these two methods.
First:
getResults(){
return this.http.get('http://localhost/api.php')
.toPromise()
.then( data => data.json() );
}
Error Shown:
3 122412 error EXCEPTION: Uncaught (in promise): Response with status:0 for URL: null
4 122413 error ORIGINAL STACKTRACE:
5 122413 error Error: Uncaught (in promise): Response with status: 0 for URL: null
..........
Second:
getResults(){
return new Promise((resolve, reject) => {
this.http.get('http://localhost/api.php')
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, (err) => {
reject(err);
});
});
}
Error Shown:
2 925052 error EXCEPTION: Uncaught (in promise): Response with status:0 for URL: null
3 925052 error ORIGINAL STACKTRACE:
4 925053 error Error: Uncaught (in promise): Response with status: 0 for URL: null
.......
Which method should I use and what could be the issue?
回答1:
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); });
回答2:
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/
回答3:
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
});
来源:https://stackoverflow.com/questions/40367286/ionic-2-http-get-issue