Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ionic problem No 'Access-Control-Allow-Origin'

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) {...}

like image 823
bakrim Avatar asked Jul 13 '16 17:07

bakrim


People also ask

How do you fix an ionic CORS problem?

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.

Why does CORS policy no access-control-allow-origin?

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 ...

How do you solve the CORS problem in spring boot?

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.

Why am I getting a CORS error?

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.


2 Answers

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.

like image 123
Arul Avatar answered Sep 22 '22 06:09

Arul


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/

like image 25
misha130 Avatar answered Sep 18 '22 06:09

misha130