在Express路由之间传递数据以创建两个响应

时间:2017-04-14 08:21:30

标签: javascript node.js express google-visualization pug

我有一个项目,当用户按下提交按钮时,它会在我的服务器上发送数据'to'和'from'到'/ charts',即express.js。 (下面是我的一些哈巴狗脚本)。

//index.pug    
form(action="/charts" method="get")
            select
                    option(value='chart') Chart
                    option(value='report') Report
            p From:
                    input(type='date' id='from' name='from')
            p To:
                    input(type='date' id='to' name='to')
            input(type="submit" value="Submit")

在服务器端,我希望能够使用用户刚刚在SQL查询中提交的数据,其结果将作为JSON发送到我的客户端JavaScript,从而创建一些谷歌图表可视化。< / p>

//server.js
app.get('/charts', function(req, res, next) {

    var to = req.params.to;
    var from = req.params.from;

    console.log("Dates /dateRange " + to + " - " + from);

    //SQL Query
    connection.query("select date_, count(*) AS 'Total' from ( select date(insert_timestamp) date_ from test_table where api_task_type='hifd' AND insert_timestamp BETWEEN '" + from + "' AND '" + to + "')a group by date_ order by date_", function(err, rows, fields){
    if(!err){
    var table = [];
    for (var i in rows) {
            table.push({
                    date: String(rows[i].date_.getFullYear() + '-' + (rows[i].date_.getMonth() + 1) + "-" + rows[i].date_.getDate()),
                            Record_Count: (rows[i].Total),
                    });
            console.log(rows[i]);
    }
    console.log("The JSON data is: " + table);
    res.json(table);
    }
});

});

我遇到的问题是,在发送json数据的同时,我想渲染我的可视化页面(chart.pug),但是表示不允许你发送多个响应。所以我想要像:

app.get('/chartQuery', function(req, res, next) {

    var to = req.params.to;
    var from = req.params.from;

    console.log("Dates /dateRange " + to + " - " + from);

    //SQL Query
    connection.query("select date_, count(*) AS 'Total' from ( select date(insert_timestamp) date_ from test_table where api_task_type='hifd' AND insert_timestamp BETWEEN '" + from + "' AND '" + to + "')a group by date_ order by date_", function(err, rows, fields){
    if(!err){
    var table = [];
    for (var i in rows) {
            table.push({
                    date: String(rows[i].date_.getFullYear() + '-' + (rows[i].date_.getMonth() + 1) + "-" + rows[i].date_.getDate()),
                            Record_Count: (rows[i].Total),
                    });
            console.log(rows[i]);
    }
    var stringtable = JSON.stringify(table);
    console.log("The JSON data is: " + table);
    res.json(table);
    //Render the chart page
    res.render('chart');
    }
});

});

任何想法如何实现这一目标?我想发送从SQL查询中提取的json数据并一次性渲染我的页面。

修改

在客户端javascript我的代码如下:

function drawHorizontalBar() {

$.getJSON('/charts', function(json) {

    var newJson = json.map(Object.values);


    var options = {
    chart: {
      title: 'Record Count Over time',
      chartArea: {width:'100%'}
    },
    height:400,
    hAxis: {
      title: 'Record Count',
      minValue: 0,
    },
    vAxis: {
      title: 'Date'
    },
    bars: 'horizontal'
  };

    var dataTable = new google.visualization.DataTable();
    dataTable.addColumn('string', 'Date');
    dataTable.addColumn('number', 'Record Count');
    dataTable.addRows(newJson);

    var material = new google.charts.Bar(document.getElementById('test_div'));
    material.draw(dataTable, options);
});

}

如果我使用建议:

res.render('chart', { table: table });

如何在我的客户端javascript中访问表?任何想法

1 个答案:

答案 0 :(得分:0)

根据Express 4文档,您可以在render方法中传递一个变量

// pass a local variable to the view
res.render('chart', { data: table }, function(err, html) {
  // ...
});

https://expressjs.com/en/api.html#res.render

然后您可以使用以下方式在客户端Jade / Pug中访问您的表:

#{data.something} // #{table.something}