Search code examples
angularsymfonycorssymfony-3.4nelmiocorsbundle

How to properly allow CORS origin in Symfony API


Deploying my angular5+symfony app I found some errors, no matters which my configuration is I still getting:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api-name.real-local-domain.cu/app_dev.php/api/some-url (Reason: CORS preflight channel did not succeed).

The problem is that the path /some-url/adicionar (post) works but nothing else. I've followed some docs to setup the CORS origin globally either in apache or virtual host but still not working.

Finally this is my nelmio config which is supposed to allow all origins

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
        max_age: 3600
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']

Does some have an idea what's happening

Working with Angular 5+Symfony 3.4.6(fosrest+nelmiocors)+Apache2 on Ubuntu 16.04

UPDATED

Also when I access to the deployed server I can see the records of the request in my table but others can't. Others received a 403 code response but the usual is to get the CORS header issue.

My app structure:

  • Enterprise domain: realdomain.cu
  • Virtual server: Ubuntu 16.04
  • Backend project:Symfony 3.4.6+corsbundle+fosrest
  • backend api: project-api.realdomain.cu
  • frontend : project.realdomain.cu

both virtualhost are configured with a .conf under apache/sites-available


Solution

  • Do you need:

    origin_regex: true
    

    on your '^/api/' section?

    Also in your '^/' section, hosts is specified as:

    hosts: ['^api\.']
    

    should it not be:

    hosts: ['^api-name\.']