我尝试使用这两种方法进行public static void main(String[] args)
{
int height = heightInInches();
int weight = weightInPounds();
System.out.println("Height in inches: " + height);
System.out.println("Weight in pounds: " + weight);
System.out.println(outputBMI(height,weight));
}
调用。
首先:
http.get()
错误显示:
getResults(){
return this.http.get('http://localhost/api.php')
.toPromise()
.then( data => data.json() );
}
第二
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
..........
错误显示:
getResults(){
return new Promise((resolve, reject) => {
this.http.get('http://localhost/api.php')
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, (err) => {
reject(err);
});
});
}
我应该使用哪种方法以及可能出现的问题?
答案 0 :(得分:3)
状态响应:URL为0:null
这似乎与CORS问题有关...请检查您的后端代码中是否启用了CORS。
我应该使用哪种方式?
http.get()
返回一个Observable,因此使用它的一种方法是
getResults(){
this.http.get('http://localhost/api.php')
.map(res => res.json());
}
然后当你调用那个方法时,你需要这样做:
this.yourService.getResults().subscribe((data) => { console.log(data); });
如果您需要返回承诺,那么您可以这样做:
getResults(){
this.http.get('http://localhost/api.php')
.map(res => res.json())
.toPromise();
}
并像这样使用
this.yourService.getResults().then((data) => { console.log(data); });
答案 1 :(得分:1)
如果您在浏览器中进行测试并遇到CORS问题,离子有一个解决方案 你应该在ionic.config中加入类似的东西,当运行离子服务时,这将为你代理API而不用CORS。
{
// ...
"proxies": [{
"path": "/api",
"proxyUrl": "http://xxxxxxxxx"
}]
}
答案 2 :(得分:0)
看起来这是一个CORS问题。通常,您必须将允许访问API的所有域列入白名单。但是因为你正在编写一个Ionic App,所以一旦你构建你的应用并在你的设备上运行它就无所谓了。这就是我建议安装一个允许你禁用CORS的浏览器插件的原因。
您的两个代码段都做同样的事情。如果你不想使用observable,我可能会选择第一个选项:
getResults() {
return this.http.get('http://localhost/api.php')
.toPromise();
}
然后:
this.service.getResults().then(data => {
// Do something with data
});