phpsymfonycorsnelmiocorsbundle

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


I wanted to access my Backend through a frontend request but i always get the following error: Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have already tried to use the Nelmio Bundle and searched through different places but nothing worked. I mainly followed this tutorial: https://codereviewvideos.com/course/beginners-guide-back-end-json-api-front-end-2018/video/symfony-4-cors-json-api

I also tried to use headers within my function, but the result is the same error message:

//Controller
      $response = new Response();
            $response->headers->set('Content-Type', 'application/json');
            $response->headers->set('Access-Control-Allow-Origin', '*');

//nelmio_cors.yaml:
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:
        '^/': null

//.env File:

    ###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://.*?$
###< nelmio/cors-bundle ###

Solution

  • I found out that Azure offers a build in function to enable and manage the CORS. This function seems to be overriding the CORS Package that i tried to use within my function. So you just have to go to azure portal -> your App Service -> and click on CORS (under API)