Allow CORS on symfony 4

Felipe Chagas picture Felipe Chagas · Feb 6, 2019 · Viewed 21.6k times · Source

I recently needed to allow CORS and on my search for a solution I found nelmio/NelmioCorsBundle.

For the begging I can allow request from any origin, so this is my app/config/config.yml:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
        max_age: 3600
        origin_regex: false 

It worked for GET requests only, any POST request returns:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

I don't need necessarily to work with this bundle, at the begging i tried to uncomment TRUSTED_HOSTS and set it with my domain on dotenv file but it was for no use. Also I didn't found any help about this TRUSTED_HOSTS in docs.

So any help with this bundle or any other solution to CORS on symfony I would be glad.


As asked I'm updating with my current config of nelmiocors:

# app/config/config.yml

# Nelmio CORS Configuration
nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/':
          origin_regex: true
          allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
          # allow_origin: ['^http://localhost:[0-9]+']
          allow_headers: ['*']
          allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
          # allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
          max_age: 3600
          # hosts: ['^api\.']

Answer

Felipe Chagas picture Felipe Chagas · Feb 7, 2019

Don't know what exactly was wrong, but as one of the comments helped (the person who helped might have deleted his own comment).

I end up with this configuration to Nelmio CORS:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['*']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': ~

And after that cleared the cache from cli and manually and it worked.

My guess on what I was doing wrong: When I first configured Nelmio CORS I didn't cleared the cache and consequently it didn't work. After that I tried some other combinations of configuration and it didn't work either even when I cleared the cache. This makes me thing that the code should work from the begging if i didn't forget to clear the cache, after this I used invalid configuration and obviously clearing the cache this wouldn't work. In sum, it was a beginners mistake.