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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8472333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:48:37  来源:igfitidea点击:

Symfony2 - how can I set custom CORS Headers?

phpsymfonycors

提问by Edge

I want to set following Headers for TWIG Template from within my DefaultController:

我想从我的 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, *');

Any suggestions how to do that?

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

回答by pleerock

from thisarticle:

这篇文章:

CorsListener.php

监听器.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

服务.yml

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

回答by Steven

Using the response class:

使用响应类:

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

Source/Documentation

来源/文件

回答by TroodoN-Mike

If its inside controller then use this:

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

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

Just replace Content-Type with your header key and xml with value ... etc

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

回答by egeogretmen

If you are using the render()method of the controller, then you can add the necessary headers like below because render()method returns a Response object:

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

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