如何从Node.js获取数据(数组,Json文件)到我的前端

时间:2017-05-11 07:00:29

标签: javascript json node.js frontend backend

我从我的数据库中获取数据到我的node.js文件中,现在我希望它能够以某种方式发送到我的javascript前端。 如果我完全按照它现在的方式完成,请让我知道,所以我可以在这里或那里进行调整,甚至重新编写它。

Routes.js (这应该是所有魔法发生的地方)

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;

Index.js (这里我们只是路由到我们的Routes.js文件)

/**
 * 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');
});

Pug文件(我尝试使用Google Chart创建我的数据图表并显示它们,但因此,我需要数据库中的数据)

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);

修改

我希望数据库中的数据位于前端的Javascript中。也许这次更清楚了?我不知道:)。

0 个答案:

没有答案