CORS Api with symfony
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 ;
}
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