CORS Api with symfony
I advise you to use NelmioCorsBundle:
https://github.com/nelmio/NelmioCorsBundle
This bundle allows you to send Cross-Origin Resource Sharing headers with ACL-style per-URL configuration.
Is very useful for CORS problem
I used Symfony 5
and Wordpress
this code in the file public/index.php
works perfectly.
header('Access-Control-Allow-Origin: *');header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");header("Allow: GET, POST, OPTIONS, PUT, DELETE");$method = $_SERVER['REQUEST_METHOD'];if ($method == "OPTIONS") { die();}
Also, I remove package cors
.. This Bundle doesn't work for me
I'm not sure that's the right way, but I resolved for me:
- Create new event subscriber (like
ResponseSubscriber
) - Listen
KernelEvents::RESPONSE
event - In your handler add the following:
if ($event->getRequest()->getMethod() === 'OPTIONS') { $event->setResponse( new Response('', 204, [ 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers' => 'DNT, X-User-Token, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type', 'Access-Control-Max-Age' => 1728000, 'Content-Type' => 'text/plain charset=UTF-8', 'Content-Length' => 0 ]) ); return ;}