Ionic 3 problems with get in estorage

Asked

Viewed 36 times

0

I have the following problem.

  apelidoCidade(){
  let cidade =  this.storage.get('apelidocidade').then(res => console.log(res));
   
     return cidade;
   
  }
  getbanner(){
   
    let url = 'http://localhost/'+  this.apelidoCidade() +'/index.php?component=json&action=bannerinicio';
    let data: Observable<any> = this.http.get(url);
    data.subscribe(result => {
    this.banners = result;  
   
     
    });
  }

It returns me the city on the log console. But give me the following error on the console

:8100/#/home:1 Access to Xmlhttprequest at 'http://localhost/[Object%20Promise]/index.php? Component=json&action=bannerinicio' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource.

How can I solve this problem?

1 answer

1

Well, there are at least 2 errors.

1 - You are making a request to a local server that does not have CORS enabled. You can see more about CORS here. In short, applications in Ionic are a webview. When your application tries to access data from somewhere, it’s as if your browser is on a site (localhost:8100) trying to access data from another site (localhost:80). This by default is blocked as it may be malicious code that is trying to get information from a site without the user’s knowledge.

To solve this problem, you have 2 options: prepare your server to release CORS from requests coming from your application or make requests using http plugin that simulates a real device in http calls. Both solutions described here.

2 - The other problem is that your "nicknamed Age()" function returns a Promise, and you are not waiting for it to be resolved before calling the http request. In this case, the value returned when you call "this.nickname City()" is not the city, as Promise has not yet finished executing. You could change the function to something like this:

apelidoCidade(){
     this.storage.get('apelidocidade').then(res => {
     console.log(res);
     return res;
    });

For more clarity on Promise, you can go at that link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.