简体   繁体   English

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

[英]Pass data between Express routes in order to create two responses

I have a project where when the user presses the submit button it sends the the data 'to' and 'from' to '/charts' on my server, which is express.js. 我有一个项目,当用户按下提交按钮时,它将在我的服务器上将数据“ to”和“ from”发送到“ / charts”,即express.js。 (Below is some of my pug script). (下面是我的哈巴狗脚本)。

//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")

On the server side, I want to be able to use the data the user has just submitted in an SQL query, the result of which will be sent as JSON to my client-side JavaScript which creates some google charts visualizations. 在服务器端,我希望能够使用用户刚刚在SQL查询中提交的数据,其结果将作为JSON发送到我的客户端JavaScript,这会创建一些Google图表可视化。

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

});

The problem I am having is that, along with sending the json data, I want to render my visualization page (chart.pug), but express doesnt allow you to send more than one response. 我遇到的问题是,与发送json数据一起,我想呈现我的可视化页面(chart.pug),但是express不允许您发送多个响应。 So I would like something like: 所以我想要这样的东西:

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

});

Any ideas how to achieve this? 任何想法如何实现这一目标? I want to send my json data extracted from the SQL query and render my page, all at once. 我想一次发送从SQL查询中提取的json数据并呈现我的页面。

EDIT 编辑

On the client side javascript my code is as follows: 在客户端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);
});

}

If I use the suggested: 如果我使用建议:

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

How do I access table in my client side javascript? 如何在客户端JavaScript中访问表格? Any ideas 有任何想法吗

According to Express 4 docs, you can pass a variable in the render method 根据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 https://expressjs.com/en/api.html#res.render

Then you can access your table in client side Jade/Pug using: 然后,您可以使用以下方法在客户端Jade / Pug中访问您的表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM