Symfony2 - 如何设置自定义CORS标头?

时间:2011-12-12 09:37:32

标签: php symfony cors

我想在DefaultController中设置以下TWIG模板的标题:

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://www.mywebsite.com');
header('Access-Control-Allow-Headers: Content-Type, *');

有任何建议怎么做?

4 个答案:

答案 0 :(得分:31)

来自this文章:

<强> CorsListener.php

<?php
namespace MyCorp\MyBundle\Listener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class CorsListener
{
    public function onKernelResponse(FilterResponseEvent $event)
    {   
        $responseHeaders = $event->getResponse()->headers;

        $responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
        $responseHeaders->set('Access-Control-Allow-Origin', '*');
        $responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
    }   
}

<强> services.yml

app.cors_listener:
    class:      MyCorp\MyBundle\Listener\CorsListener
    tags:
       - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

答案 1 :(得分:30)

使用响应类:

use Symfony\Component\HttpFoundation\Response;
$response = new Response();
$response->headers->set('Content-Type', 'text/html');
$response->send();

Source/Documentation

答案 2 :(得分:3)

如果它的内部控制器然后使用它:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        ...    
        $response = new Response($xmlContent);
        $response->headers->set('Content-Type', 'xml');
        $response->headers->set('Another-Header', 'header-value');
        return $response;
    }
}

只需将您的标题键替换为Content-Type,将xml替换为值...等等

答案 3 :(得分:2)

如果您正在使用控制器的render()方法,那么您可以添加如下所示的必要标头,因为render()方法返回一个Response对象:

$response = $this->render('AppBundle:Post:index.html.twig', array('someArgs' => $someArgs));
$response->headers->set('Content-Type', 'text/html');
return $response;