Thursday, 11 May 2017

How do I get Data (Array, Json File) from Node.js into my Frontend

Hello and good morning,

i am getting data from my databases into my node.js and now i want it to be responded in someway to my javascript frontend. If im totally off with the way it by now, let me know about it, so i can maybe tweak here and there or even write it new.

Routes.js

This should be the place where all the magic is happening.

> var express = require('express'); const routes =
> require('express').Router(); var mysql = require('mysql'); var path =
> require('path');
> 
> routes.get('/', function (req,res) {
>     res.redirect('/kamis'); });
> 
> routes.get('/kamis', function (req, res) {
>     createDatabasePool(req, res); });
> 
> /*
> * Redirect to /kamis/:channelName if URL is shorted by hand
> * example: /kamis/ -> by clicking any channel in the user interface would adjust the URL to /kamis/kamis/:channelName
> */ routes.get('/kamis/kamis/:channelName', function (req, res) {
>     res.redirect('/kamis/' + req.params.channelName); });
> 
> routes.get('/kamis/:channelName', function (req, res) {
>     createDatabasePool(req, res); });
> 
> routes.get('/kamis/:channelName/:groupId', function (req, res) {
>     createDatabasePool(req, res); });
> 
> routes.get('/kamis/:channelName/:groupId/:kpiId', function (req, res)
> {
>     createDatabasePool(req, res); });
> 
> 
> function createDatabasePool(req, res) {
> 
>     /* default database is kamis
>      * channelName is indicator for the database
>      * checks if channelName is set, if not use default
>      * kamis_ is prefix for every ChannelDatabase in KamisOld
>      */
>     var database;
> 
>     if(req.params.channelName != null) {
>         database = 'kamis_' + req.params.channelName;
>     } else {
>         database = 'kamis';
>     }
> 
>     var pool = mysql.createPool({
>         host: 'localhost',
>         user: 'root',
>         password: '',
>         database: database,
>         debug: false
>     });
> 
>     pool.getConnection(function (err, connection) {
>         if (err) {
>             res.json({"code": 100, "status": "Error in connection database"});
>             return;
>         }
>         console.log('connected as id ' + connection.threadId);
> 
>         if (database === 'kamis') {
>             getAllChannelNames(res, connection)
>         } else if(req.params.channelName != null && req.params.groupId == null && req.params.kpiId == null) {
>             getGroupsByChannelName(req, res, connection);
>         } else if( req.params.channelName != null && req.params.groupId != null && req.params.kpiId == null) {
>             getKpisByGroupId(req, res, connection);
>         } else if (req.params.channelName != null && req.params.groupId != null && req.params.kpiId != null) {
>             getKpiDataById(req, res, connection);
>         }
> 
>         connection.on('error', function (err) {
>             res.json({"code": 100, "status": "Error in connection database"});
>         });
>     }); }
> 
> function getAllChannelNames (res, connection) {
>     connection.connect(function (err) {
>         if (!err) {
>             console.log("Database is connected");
>         } else {
>             console.log("Error connecting database");
>         }
>     });
>     connection.query('SELECT channel from kamis_mod_kamis_Channels', function (err, rows) {
>         if (!err){
>             res.render('channels', {elements: rows});
>             console.log('The solution is: ', rows);
>         }
>     }); }
> 
> function getGroupsByChannelName(req, res, connection) {
>     connection.query("SELECT id from groups", function (err, rows) {
>         connection.release();
>         if (!err) {
>             res.render('groups', {elements: rows, channelName:req.params.channelName});
>             console.log(rows);
>         }
>     }); }
> 
> function getKpisByGroupId(req, res, connection) {
>     connection.query("SELECT id from kpis where groupid = ?", [req.params.groupId],
>         function (err, rows) {
>             connection.release();
>             if (!err) {
>                 res.render('kpis', {elements:rows, groupId:req.params.groupId, channelName:req.params.channelName});
>                 console.log(rows);
>             }
>         }); }
> 
> 
> function getKpiDataById(req, res, connection) {
>     connection.query("SELECT * from kpi_"+req.params.kpiId+"",
>         function (err, rows) {
>             connection.release();
>             if(!err) {
>                 //res.sendFile(path.join(__dirname + '/views/googleChartTest.html')), {elements:rows};
> 
>                 res.render('kpiContent',{elements:rows});
> 
>                 //console.log(rows);
>                 //console.log('routes.js meldet sich hier');
>             }
>         }); }
> 
> 
> routes.post('/', function(req, res){  res.send('POST route on
> route.'); });
> 
> //export this routes to use in our index.js module.exports = routes;

Here is my Index.js

Here we just Route to our Routes.js file

/**
 * Created by ludwigdev on 05.05.17.
 */

var express = require('express');
var app = express();
var routes = require('./routes');

app.set('view engine', 'pug');
app.set('views','./views');

app.use('/', routes);

app.listen(3000, function() {
    console.log('App listening on port 3000');
});

Here is the pug file

Im trying to use Google Chart to create Graphs of my Data and display them but therefor, i need the data from my Database.

doctype html
html
    head
        title Google Charts Tutorial
        script(type='text/javascript', src='https://www.gstatic.com/charts/loader.js')
        script(type='text/javascript').
            google.charts.load('current', {packages: ['corechart']});
    body

        #container(style='width: 550px; height: 400px; margin: 0 auto')
        #container1(style='width: 550px; height: 400px; margin: 0 auto')
        script(language='JavaScript').
            function drawChart() {
                // Define the chart to be drawn.
                var data = new google.visualization.DataTable();
                data.addColumn('string', 'Browser');
                data.addColumn('number', 'Percentage');
                data.addRows([
                    ['Firefox', 45.0],
                    ['IE', 26.8],
                    ['Chrome', 12.8],
                    ['Safari', 8.5],
                    ['Opera', 6.2],
                    ['Others', 0.7]
                ]);
                // Set chart options
                var options = {'title':'Browser market shares at a specific website, 2014',
                    'width':550,
                    'height':400};
                // Instantiate and draw the chart.
                var chart = new google.visualization.PieChart(document.getElementById('container'));
                chart.draw(data, options);
            }
            google.charts.setOnLoadCallback(drawChart);
        script(language='JavaScript').
            function drawChart1() {
                // Define the chart to be drawn.
                // **Here i need the data from the database**
                var data = google.visualization.arrayToDataTable([
                    ['Year', 'Alt-Kamis', 'Kamis5.0'],
                    ['2015',  4000,      0],
                    ['2016',  2500,      0],
                    ['2017',  1000,       0],
                    ['2018',  0,      9000]
                ]);

                    /*//var data = 'elements';
                    //console.log('kpiContent meldet sich hier')*/

                var options = {
                    title: 'Company Performance',
                    hAxis: {
                        title: 'Year',
                        titleTextStyle: {
                            color: '#333'
                        }
                    },
                    vAxis: {
                        minValue: 0
                    }
                };
                // Instantiate and draw the chart.
                var chart = new google.visualization.AreaChart(document.getElementById('container1'));
                chart.draw(data, options);
            }
            google.charts.setOnLoadCallback(drawChart1);

I hope u can help me out.

Thanks in advance. Kai



via Kai

No comments:

Post a Comment