NelmioCorsBundle icon indicating copy to clipboard operation
NelmioCorsBundle copied to clipboard

[Symfony 5, symfony serve on php 7.3.12 ] blocked by CORS policy

Open nawatend opened this issue 4 years ago • 13 comments

I have been digging google for two days for my CORS Error from React App To Symfony REST API.

My react webapp axios post request: image

React CORS Error image

I have REST API(Symfony 5).

Symfony Serving image

nelmio_cors.yaml image

.env image

bundles.php image

I also tried other alternatives like setting headers in index.php in public folder. didnt work.

Any help would be nice :D

nawatend avatar Apr 03 '20 21:04 nawatend

Hey,

try to send your request to https://127.0.01:8000/exercises and I think you don't need to configure your header from the client site with axios.

skanderphilipp avatar Apr 22 '20 11:04 skanderphilipp

@nawatend I have the same issue, do you have some news about that ? Thanks in advance.

sined79 avatar Jun 16 '20 10:06 sined79

Same Problem here

benblub avatar Jun 26 '20 13:06 benblub

@nawatend I have the same issue, do you have some news about that ? Thanks in advance.

I couldn't solved it in time, so I switched entire backend to Node.js

nawatend avatar Jul 03 '20 07:07 nawatend

Same Problem here

ahmetilhann avatar Jul 08 '20 11:07 ahmetilhann

I solved to my problem. Let me tell you maybe it will help you. There was no problem with this package. I created a new response object in subscribers. If the package adds a parameter to the header, it becomes ineffective.

Old response:


namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class ResponseSubscriber implements EventSubscriberInterface
{
    public function onKernelResponse(ResponseEvent $event)
    {
        if ($event->getResponse()->getStatusCode() == 200) {
            $data = json_decode($event->getResponse()->getContent(), true);
            if (!isset($data['data'])) {
                $res['data'] = $data;
                $event->setResponse(new JsonResponse($res));  // I created a new response object here
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            'kernel.response' => 'onKernelResponse',
        ];
    }
}

New response and solution:


namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class ResponseSubscriber implements EventSubscriberInterface
{
    public function onKernelResponse(ResponseEvent $event)
    {
        if ($event->getResponse()->getStatusCode() == 200) {
            $data = json_decode($event->getResponse()->getContent(), true);
            if (!isset($data['data'])) {
                $res['data'] = $data;
                $event->getResponse()->setContent(json_encode($res));
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            'kernel.response' => 'onKernelResponse',
        ];
    }
}

ahmetilhann avatar Jul 08 '20 14:07 ahmetilhann

Had the same problem. Solved it by using configuration from here https://packagist.org/packages/nelmio/cors-bundle and by adding allowed headers which are passed from frontend.

inserting mine below:

image

nelmio_cors: defaults: allow_credentials: false allow_origin: [] allow_headers: [] allow_methods: [] expose_headers: [] max_age: 0 hosts: [] origin_regex: false forced_allow_origin_value: ~ paths: '^/api/': allow_origin: ['*'] allow_headers: ['X-Custom-Auth', 'Content-type'] allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] max_age: 3600 '^/': origin_regex: true allow_origin: ['^http://localhost:[0-9]+'] allow_headers: ['X-Custom-Auth'] allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] max_age: 3600 hosts: ['^api.']

gcilinskas avatar Oct 13 '20 19:10 gcilinskas

I just the same error. After spending 1 hour blaming it on this bundle, I just realized there was any problem with the configuration. I was just calling the wrong URL. If the browser returns a cors error, open this link directly in the browser and make sure it's not returning a 404 error code. I have set the link to http://myhost/link instead of http://myhost/index.php/link.

Guervyl avatar Feb 08 '21 06:02 Guervyl

I am having the same problem, apparently, the symfony-cli server removes the headers needed for Nelmio cors work, using the PHP internal server the Nelmio works correctly.

Using the following version: "nelmio/cors-bundle": "^2.1", "symfony/framework-bundle": "5.2.*" Symfony CLI version v4.23.0

giroberto avatar Feb 23 '21 01:02 giroberto

Using symfony-cli server completely normal and no issue for me.

I am having the same problem, apparently, the symfony-cli server removes the headers needed for Nelmio cors work, using the PHP internal server the Nelmio works correctly.

Using the following version: "nelmio/cors-bundle": "^2.1", "symfony/framework-bundle": "5.2.*" Symfony CLI version v4.23.0

fd6130 avatar Feb 23 '21 03:02 fd6130

hello les dev ! quelqu'un a trouvez une solution pérennes ? moi je suis obligé pour continuer a étudier de passer par un navigateur sans sécurité!! pas le top...

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

kendryk avatar Mar 25 '21 07:03 kendryk

@nawatend @giroberto @ahmetilhann I think the issue is HTTP. In my case, accessing the backend with HTTPS prevents CORS policy. Symfony CLI supports self-signed certificates. To enable:

symfony server:ca:install

aliemre avatar Apr 02 '21 07:04 aliemre

Had the same problem. Solved it by using configuration from here https://packagist.org/packages/nelmio/cors-bundle and by adding allowed headers which are passed from frontend.

inserting mine below:

image

nelmio_cors: defaults: allow_credentials: false allow_origin: [] allow_headers: [] allow_methods: [] expose_headers: [] max_age: 0 hosts: [] origin_regex: false forced_allow_origin_value: ~ paths: '^/api/': allow_origin: ['*'] allow_headers: ['X-Custom-Auth', 'Content-type'] allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] max_age: 3600 '^/': origin_regex: true allow_origin: ['^http://localhost:[0-9]+'] allow_headers: ['X-Custom-Auth'] allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] max_age: 3600 hosts: ['^api.']

this worked for me ! thanks a lot

apeza avatar Jul 18 '21 14:07 apeza

If anyone has ideas how to improve the docs to reduce confusion please feel free to send a PR :)

Seldaek avatar Feb 15 '23 13:02 Seldaek

Hey,

try to send your request to https://127.0.01:8000/exercises and I think you don't need to configure your header from the client site with axios.

work for me

tetar998 avatar Apr 03 '23 13:04 tetar998

Bonjour à tous. J'ai le même problème, seulement que à mon niveau, mon url est redirigé vers la page de connexion du backend. Du coup au lieu d'obtenir le fichier souhaité, j'obtiens la page de connexion du backend symfony. Si non que cors est bien configuré à mon niveau. Je ne comprends pas pourquoi ça fait une redirection. reponse: Response {type: 'cors', url: 'https://127.0.0.1:8000/login', redirected: true, status: 200, ok: true, …} body : (...) bodyUsed : true headers : Headers {} ok : true redirected : true status : 200 statusText : "" type : "cors" url : "https://127.0.0.1:8000/login" [[Prototype]] : Response

or que je fais la requête à la bonne url pourtant:

` const apiUrl = 'https://127.0.0.1:8000/dashboard/photo/download/' + imageId + '/' + imageNumber;

  fetch(apiUrl, {
    method: 'GET',
    responseType: 'blob',
    credentials: 'include', // Spécifie le type de réponse attendu comme Blob
  })
 ....

` Si quelqu'un a une idée, je suis preneur :)

BILL11715 avatar Aug 06 '23 18:08 BILL11715