Create Three Symfony Back Ends - Part #15 - CORS, your API, and the outside world
We've now got a tested and working Symfony 4 API that allows us to GET, POST, PUT, PATCH, and DELETE our Album resources. There are lots of extra tasks that we could do here, but there's one that I'd immediately recommend we do, and this is one that is a real "gotcha". During development we do everything on our local machine, often working with a webserver on localhost, or internal IP address. Symfony makes this super easy for us, as we have already seen - bin/console server:start - and we are away. Given that we now have a working Symfony 4 API, it makes sense that we'd like to get our shiny new code out there on to the world wide web. Or, to put it another way, we want to ship this code to production. But there's a problem. By default, our Symfony 4 API will be open for access only to requests coming from the same point of origin. This isn't a problem specific to Symfony. This is Cross-Origin Resource Sharing (CORS) hard at work. You could be using Laravel, or Django, or Spring, or raw PHP and still hit this issue. What this means is that if we have our Symfony 4 API on a sub-domain, e.g. ';https://api.oursite.com', yet we have our front end on ';https://www.oursite.com', then HTTP requests from the front end to the back end will fail: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.oursite.com/album/1. (Reason: CORS header 'Access-Control-Allow-Origin' missing)." Now this is exactly the sort of annoyance that will highly likely catch you out the first time you need to put your API out into production.