Skip to main content

CORS API supporting Symfony3 + Angular2

Is your API giving you trouble with a missing Access-Control-Allow-Origin header error?

Perhaps you enjoy living on the bleeding edge, and you’ve decided to build an app with Symfony3 + Anglar2 and you’ve seen this before?

XMLHttpRequest cannot load http://myapp.dev. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

After many days of stressing and confusion I’ve identified what I believe to be the “easiest” solution to this problem, specifically if you’re using nginx.

Install nginx-extras (Debian/Ubuntu)

Configure NGINX

Failed Solutions

  1. I attempted nelmio/cors-bundle with limited success and various odd issues. Particularly the response would come back successful, but the browser would still react as if there was a 404 on the response Header. This resulted in Angular2 acting as though the response wasn’t even worth processing, and so it didn’t.
  2. I attempted hard-coding the header directly to the $response object in my frontend controller, but this made me feel dirty and ultimately was ignored by nginx anyway. I also would be shocked if this worked in any real environment using a load-balancer of any kind.
  3. Building a simplified version of nelmio/cors-bundle via a CorsListener EventListener yielded similar results to above in both respects. This appeared to be completely ignored by nginx, and resulted in no tangible change. An example implementation can be found here: https://www.snip2code.com/Snippet/87161/Allow-CORS-in-symfony2