如何设置自定义标头

如何设置自定义标头

本文介绍了Symfony2 - 如何设置自定义标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b $ pre> header('Access-Control-Allow-方法: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,*');

有任何建议怎么做?

解决方案

from 文章:



CorsListener.php

 <?php 
命名空间MyCorp \ MyBundle \Listener;

使用Symfony \Component\HttpKernel\Event \FilterResponseEvent;
$ b $ class CorsListener
{
public function onKernelResponse(FilterResponseEvent $ event)
{
$ responseHeaders = $ event-> getResponse() - >头;

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


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

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?

解决方案

from this article:

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 }

这篇关于Symfony2 - 如何设置自定义标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:11