How to Enable Preflight CORS in PHP for Angular HTTP requests

When testing Ionic or Angular app you might need to set CORS policy to access a service on a different domain. One way to do this in PHP for testing is to send OK responses for all OPTIONS requests. (If you are testing POST and GET requests)

In your php file set:

// change to your app origin
header('Access-Control-Allow-Origin: http://localhost:8100');
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language, X-Authorization");
header('Access-Control-Max-Age: 86400');

    // The request is using the POST method
    header("HTTP/1.1 200 OK");


Don’t ship this test code, this is just for your internal testing of http requests.

Origin is not allowed by Access-Control-Allow-Origin Error in Ionic

If you got this issue in Ionic:

Origin http://localhost:8100 is not allowed by Access-Control-Allow-Origin.

It is because you are running node.js and ionic serve project on localhost and trying to access two different ports which causes a cross origin access error.

To fix this simply edit your ionic.project file to map out the linking like this:

  "name": "proxy-example",
  "app_id": "",
  "proxies": [
      "path": "/signUp",
      "proxyUrl": "http://localhost:3000/signUp"
      "path": "/checkSession",
      "proxyUrl": "http://localhost:3000/checkSession"
      "path": "/login",
      "proxyUrl": "http://localhost:3000/login"
      "path": "/logout",
      "proxyUrl": "http://localhost:3000/logout"

Now in your Ionic project you can call localhost:8100/login for example and it will call localhost:3000/login which the port node.js server is running on.

Web App Only Solution

If you are only making a web app for the browser and not running as a native app, then you can just move the angular portion of the code into the server part.

Copy the /www folder from your frontend into the server /public folder. You can then access your UI from http://localhost:3000.

I hope this makes sense to you.