Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my Symfony application, I am using google charts.

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.

<?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>
like image 622
Sébastien Avatar asked Dec 05 '22 22:12

Sébastien


2 Answers

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.

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.

like image 176
Luzado Avatar answered Dec 08 '22 12:12

Luzado


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');
    }
}
like image 24
Thomas Decaux Avatar answered Dec 08 '22 10:12

Thomas Decaux