Symfony2在每个响应上都返回CrossDomain标头

时间:2014-06-19 14:04:38

标签: php symfony cross-domain cors

有没有办法配置我的应用程序以返回每个响应的特定标头?

我正在开发一个restful api,我需要支持跨域请求,我一直在看CORS,但我需要在每个响应中返回这样的标题:

  • Access-Control-Allow-Credentials'true
  • Access-Control-Allow-Origin'任意客户
  • 访问控制 - 允许 - 方法'GET,PUT,POST,DELETE,OPTIONS'
  • Access-Control-Allow-Headers,'X-CSRF-Token,X-Requested-With,Accept,Accept-Version, - - Content-Length,Content-MD5,Content-Type,Date,X-Api-版本

1 个答案:

答案 0 :(得分:0)

您可以创建自定义ResponseListener并为每个回复设置标题:

namespace Acme\DemoBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();

        // only do something on some situations
        if (false === strpos($request->headers->get('Foobar'), 'barfoo')) {
            return;
        }

        // set the custom header of the response
        $event->getResponse()->headers->set('Acme', 'demo');
    }
}

然后将侦听器声明为服务:

# app/config/config.yml
services:
    kernel.listener.your_listener_name:
        class: Acme\DemoBundle\EventListener\ResponseListener
        tags:
            - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

http://symfony.com/doc/current/cookbook/service_container/event_listener.html