1

I have a PHP REST service and a Ionic2 project that 'out of the box' runs on Node.js localhost:8100. The REST service runs on my computer on localhost:80. When I want to do calls from Ionic2 (Angular2) to my server on localhost I get this error in the browser console:

XMLHttpRequest cannot load http://localhost/app_dev.php/login. 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8100' is therefore not allowed access. 
The response had HTTP status code 404.

Wat I understand is that this is a CORS issue (Cross origin resource sharing). As I understand A way to solve this would be to change the build script in ionic to point to a front end distribution location in my Apache project and run the whole project from localhost:80. Another solution is to change the 'Access-Control-Allow-Origin' header.

  • What is the most simple straight forward solution for this problem?
Olivier de Jonge
  • 1,252
  • 2
  • 13
  • 30
  • Please see this[http://stackoverflow.com/questions/29954037/how-to-disable-options-request] and this[http://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests] – Math10 May 22 '17 at 10:36

1 Answers1

1

Checked the possible duplicates, and there was an potential ANSWER to which I want to add some more detail:

Since you are dealing with PHP, the following has worked for me by just adding on top of your php script the following:

<?php 

   header('Access-Control-Allow-Origin: *'); // this!
   header('Access-Control-Allow-Headers: Content-Type'); // and this!
   //more code here

?>

During development, you might very possibly need to enable CORS in your browser, here's an extension for CHROME

Hope this helps! :)

Olivier de Jonge
  • 1,252
  • 2
  • 13
  • 30
AJT82
  • 60,574
  • 21
  • 115
  • 147