nelmio / NelmioCorsBundle

Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
https://symfony.com/bundles/NelmioCorsBundle/
MIT License
1.89k stars 108 forks source link

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

Closed nawatend closed 1 year ago

nawatend commented 4 years ago

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

skanderphilipp commented 4 years ago

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.

sined79 commented 4 years ago

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

benblub commented 4 years ago

Same Problem here

nawatend commented 4 years ago

@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

ahmetilhann commented 4 years ago

Same Problem here

ahmetilhann commented 4 years ago

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',
        ];
    }
}
gcilinskas commented 4 years ago

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.']

Guervyl commented 3 years ago

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.

giroberto commented 3 years ago

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 commented 3 years ago

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

kendryk commented 3 years ago

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
aliemre commented 3 years ago

@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
apeza commented 3 years ago

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

Seldaek commented 1 year ago

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

tetar998 commented 1 year ago

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

BILL11715 commented 1 year ago

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 :)