javascript Symfony2:允许使用谷歌图表访问控制允许来源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29975384/
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-10-28 11:25:46  来源:igfitidea点击:

Symfony2 : allow Access-Control-Allow-Origin with google charts

javascripthtmlsymfonyxmlhttprequestsame-origin-policy

提问by Sébastien

In my Symfony application, I am using google charts.

在我的 Symfony 应用程序中,我使用的是谷歌图表。

I get an error :

我收到一个错误:

XMLHttpRequest cannot load https://www.google.com/uds/api/visualization/1.0/dca88b1ff7033fac80178eb526cb263e/ui+en.css. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foodmeup.dev' is therefore not allowed access.

I've tried to get around this by setting a listener which adds headers to the response (see the cors listener here : Symfony2 - how can I set custom Headers?) and it's not working, I get the same error.

我试图通过设置一个向响应添加标头的侦听器来解决这个问题(请参阅此处的 cors 侦听器:Symfony2 - 如何设置自定义标头?)但它不起作用,我得到了同样的错误。

<?php
namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class CorsListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
    $response = $event->getResponse();
    $responseHeaders = $response->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');

    $event->setResponse($response);
}
}

In my view I use a simple google chart :

在我看来,我使用了一个简单的谷歌图表:

<div class="piechart margin-auto" style="height: 220px;" data-completeness="{{ completeness }}"></div>

<script>var googleCharts = [];</script>
    <script type="text/javascript">

        function drawProfilePieCharts()
        {
            var completeness = $(this).data('completeness');

            var data = google.visualization.arrayToDataTable([
                ['Nom',    'Valeur'],
                ["Profil rempli à ", completeness],
                ['Manque', 100 - completeness]
            ]);

            var options = {
                backgroundColor: { fill:'transparent'},
                pieSliceBorderColor : 'transparent',
                pieHole: 0.8,
                legend: {position: 'top'},
                width: 220,
                height: 220,
                tooltip: {trigger: 'none'},
                pieStartAngle: -90,
                pieSliceTextStyle :{fontsize : 16, color: 'transparent'},
                slices: {
                    0: { color: '#09b4ff'},
                    1: { color: '#444'}
                },
                chartArea : {width: '90%', height: '90%'}
            };

            var chart = new google.visualization.PieChart(this);
            chart.draw(data, options);
        }

        googleCharts.push("$('.piechart').each(drawProfilePieCharts)");

    $(window).resize(function(){
        drawAllCharts();
    });


    google.load('visualization', '1', {packages:['corechart', 'bar', 'line']});
    var drawAllCharts = function() {
        for (var i = 0; i < googleCharts.length; i++) {
            eval(googleCharts[i]);
        }
    };

    google.setOnLoadCallback(function(){drawAllCharts()});

    </script>

回答by Luzado

Tried to just set the header on the response, and it worked:

试图只在响应上设置标头,它起作用了:

$response->headers->set('Access-Control-Allow-Origin', 'http://foodmeup.dev');

Take into account that the URL MUST BE exactly the one that's expected, with HTTP or HTTPS and no / at the end.

考虑到 URL 必须与预期的完全一致,带有 HTTP 或 HTTPS,最后没有 /。

It's possible to set more than one of these headers, in my case i used 4, HTTP and HTTPS, dev and prod servers. All worked fine.

可以设置多个标头,就我而言,我使用了 4 个,HTTP 和 HTTPS,开发和生产服务器。一切正常。

回答by Thomas Decaux

A good thing here is to use kernel events subscriber, such as:

这里的一个好处是使用内核事件订阅者,例如:

class Toto implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::RESPONSE => 'onKernelResponse'
        );
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $httpRequestOrigin = $event->getRequest()->headers->get('origin');

        $event->getResponse()->headers->set('Access-Control-Allow-Origin', $httpRequestOrigin);
        $event->getResponse()->headers->set('Access-Control-Allow-Credentials', 'true');
    }
}

回答by Manolo

Try this::

试试这个::

use Symfony\Component\HttpFoundation\Response;

$xmlContent = 'Your XML content';

$response = new Response();

$response->setContent($xmlContent);
$response->headers->set('Content-Type', 'text/xml');
$response->headers->set('Access-Control-Allow-Origin', 'http://foodmeup.dev');

// prints the headers followed by the content
$response->send();

Not tested

未测试

Edit:

编辑:

You may have to set the event response:

您可能需要设置事件响应:

$response = $event->getResponse();

$response->headers->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
    ...

$event->setResponse($response);