ExpressJS:推送数组中的查询值并路由到ejs

时间:2018-02-04 00:19:24

标签: mysql arrays express for-loop ejs

我需要获取将被路由到ejs文件的查询值。我可以使用data:rows来做到这一点。但是,这会给solution:Sandy。我只需要Sandy。下面,我将使用for循环的值rows[i]推送到数组arr,但是,只有最后一个元素保留在数组中。我尝试使用forEach循环,这会产生语法错误。任何想法/帮助将受到高度赞赏!

main.js

const express = require('express')
const app = express()
var router = express.Router()
app.set('view engine', 'ejs');

var arr = [];
var mysql = require('mysql')
var connection = mysql.createConnection({
  host     : 'host',
  port     : 'port',
  user     : 'user',
  password : 'password',
  database : 'database'
});

connection.connect()
connection.query('SELECT customer_name as solution FROM customers', function (err, rows, fields) {
    if (err) throw err
    for(var i in rows){
        arr.push[rows[i].solution];
    }
    app.get('/', function(req, res) {
        res.render('index', {data:arr});
    });
})
app.listen(3000, () => console.log('Example app listening on port 3000!'));

index.ejs

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title></title>

  <link rel="icon" href="images/favicon.png">
</head>

<body>
<<h1><%= data %></h1>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

当用户点击/路由时,应该执行您的查询,这样他们将始终从服务器接收更新的数据,也不需要创建另一个数组,您只需将查询结果传递给ejs然后遍历它:

<强> main.js

const express = require('express')
const app = express()
var mysql = require('mysql')

app.set('view engine', 'ejs');

var connection = mysql.createConnection({
host     : 'host',
port     : 'port',
user     : 'user',
password : 'password',
database : 'database'
});

connection.connect();

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

    connection.query('SELECT customer_name as solution FROM customers', function (err, rows, fields) {

        if (err) throw err;

        res.render('index', { data: rows });

    });

});

<强> index.ejs

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title></title>

<link rel="icon" href="images/favicon.png">
</head>

<body>

    <% for ( var i = 0; i < data.length; i++) { %>

        <h1><% data[i].solution %></h1>

    <% } %>

</body>

</html>