I'm working on an ionic apps. My problem is: when I try to get data from server I got this:
XMLHttpRequest cannot load https://mywebsite.com/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
I already try to add this to .htaccess:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
And this to my api page (PHP): header('Access-Control-Allow-Origin: *');
but still not working
$http.get(url).success(function(response) {...}
The correct and easiest solution is to enable CORS by returning the right response headers from the web server or backend and responding to preflight requests, as it allows to keep using XMLHttpRequest , fetch , or abstractions like HttpClient in Angular.
To allow any site to make CORS requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's Origin header and use that value to set Access-Control-Allow-Origin , and must also set a Vary: Origin header to indicate that some headers are being set ...
Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.
Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.
Put it on top of your PHP file like:
<?php
header("Access-Control-Allow-Origin: *");
// then your stuff goes here
?>
Note: as with all uses of the PHP header function, this must be before any output has been sent from the server.
This cors problem has a simple work around in ionic.
Go to your ionic.config.json (previously ionic.project) and add a proxy for example:
{
"name": "proxy-example",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://cors.api.com/api"
}
]
}
After that use "/api/" instead of "https://mywebsite.com/api" when you call your api.
For more info:
http://blog.ionic.io/handling-cors-issues-in-ionic/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With