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

2022-08-30 15:08:01

我想从我的默认控制器中为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, *');

任何建议如何做到这一点?


答案 1

这篇文章

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');
    }   
}

服务.yml

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

答案 2

使用响应类:

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

来源/文档


推荐