调用GET HTTP时,Android上的ionic3错误

时间:2018-11-14 09:33:20

标签: android http ionic-framework cors ionic3

在Ionic3中,我安装了import { HttpClientModule } from '@angular/common/http';,并在我的代码中尝试在url下方调用:

testHTTP(){
this.httpClient.get("https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463").subscribe(
  data => {
    console.log('Data : ', data);
    this.lookup = data["items"][0].title;
  }, err => {
    console.log('Error : ', err);
    this.lookup = JSON.stringify(err);
});
}

但每次失败均显示:

  

{“标头”:{“ normalizedNames”:{},“ lazyUpdate”:null,“标头”:{}},“状态”:0,“ statusText”:“未知错误”,“ url”:null ,“ ok”:false,“ name”:“ HttpErrorResponse”,“ message”:“ Http失败响应(未知url):0未知错误”,“ error”:{“ isTrusted”:true}}

当我单击Chrome上的调用testHTTP的按钮时,此对象发生CORS错误(但是我可以停用CORS并获得真实的响应)。

请问如何设置ionic http才能开始工作?

1 个答案:

答案 0 :(得分:0)

您应该使用XMLHttpRequest。而且不要忘记标题。

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463", true);

//Really important to set this header
xhr.setRequestHeader("Access-Control-Allow-Origin","http://localhost:8100"); 

xhr.onreadystatechange = function() {
   if(xhr.readyState == xhr.DONE) {
  let ResponseFromRequest = xhr.response //Response from your request   
}

}

xhr.send(null);