CORS Api with symfony

元气小坏坏 提交于 2020-05-27 01:55:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!