问题
I should make cross domain API with Symfony. There is some bundle for that?
I have tried FOS Rest Bundle but did not seem have solved my problem.
回答1:
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
回答2:
I'm not sure that's the right way, but I resolved for me:
1) Create new event subscriber (like ResponseSubscriber
)
2) Listen KernelEvents::RESPONSE
event
3) 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 ;
}
回答3:
I used on Symfony 5
this code in the file public/index.php
work 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
来源:https://stackoverflow.com/questions/46400213/cors-api-with-symfony