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.
sudo apt-get install -y nginx-extras
# setup CORS support for Api requests, and enable cache server support
add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Credentials true' always;
add_header Access-Control-Allow-Methods GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
add_header Vary Origin;
- I attempted
nelmio/cors-bundlewith 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.
- 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.
- 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