node.js – Help to plot correctly Google Chart + nodejs

Question:

Hello, you need to transfer an array from the server (nodejs) to the client, so that you can build a graph on it later. I pass an array, but on the client it says that it is not an array. Where is the error in the code?

Server:

app.post('/averageTimeInQueue', function(req, res, next) {
    var data = [
        [2012, 1000, 400, 232],
        [2005, 1170, 460, 421],
        [2006, 660, 1120, 4324]
    ];
    res.send(data);
});

Customer:

google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
      data.addColumn('number', 'Day');
      data.addColumn('number', 'Guardians of the Galaxy');
      data.addColumn('number', 'The Avengers');
      data.addColumn('number', 'Transformers: Age of Extinction');

      data.addRows(averageTimeInQueue);
      var options = {
        chart: {
          title: 'Box Office Earnings in First Two Weeks of Opening',
          subtitle: 'in millions of dollars (USD)'
        },
        width: 600,
        height: 350,
        axes: {
          x: {
            0: {side: 'top'}
          }
        }
      };

      var chart = new google.charts.Line(document.getElementById('chart_div2'));

      chart.draw(data, options);
}

function averageTimeInQueue(){
  var jsonData = $.ajax({
        url: "/averageTimeInQueue",
        async: false,
        type: 'POST'
    }).responseText;
    return jsonData;
}

Answer:

Certainly not an array, you send it as a text. Serialize it to json

on the server res.send(JSON.stringify(data));

on the client data.addRows(averageTimeInQueue()) instead of data.addRows(averageTimeInQueue) and

var jsonData = $.ajax({
    url: "/averageTimeInQueue",
    dataType: "json",
    async: false,
    type: 'POST'
}).responseText;
return JSON.parse(jsonData);
Scroll to Top