Ionic 3 problems with get in estorage
I'm having 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 in the log console. But give me the following error in console
:8100/#/home: 1 Access to XMLHttpRequest at 'http://localhost/[object%20promise] / index.php?component=json & action=bannerstart ' from origin 'http://localhost:8100 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Like me can I solve this problem?
1 answers
Well, there are at least 2 errors.
1-you are making a request to a local server that is not CORS enabled. you can see more about CORS here . In short, applications in ionic are a webview. When your app tries to access data from somewhere, it's like your browser is on one 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 website 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 the http plugin that simulates a real device in http calls. both Solutions described here.
2 - the other problem is that your function "nickname ()" returns a Promise, and you are not waiting for it to be resolved before calling the request http. In this case, the value returned when you call " this.nickname () " is not the city, as Promise has not finished executing yet. You could change the function to something like this:
apelidoCidade(){
this.storage.get('apelidocidade').then(res => {
console.log(res);
return res;
});
For more clarity about Promise, you can go to at this link.