我在使用 Express 和 ejs 查询 mysql 数据库并将结果显示为表格时遇到问题。
这就是我的 app.js 文件
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'host',
user : 'user',
password : 'password',
database : 'database'
});
module.exports.pool = pool;
...
var list = {};
app.get("/pokemon", function(req,res){
pool.query('SELECT p.pokemon_id AS `pokemon_id`, p.name AS `pokemon_name`,
t1.name AS `type1`, t2.name AS `type2`, p.evolution_level AS `evLevel` FROM `pokemon` p INNER JOIN `type` t1 ON t1.type_id=p.type1 INNER JOIN `type` t2 ON
t2.type_id=p.type2', function(err,result){
if(err){
throw err;
} else {
list = {listResults: result};
res.render('listResults', list);
}
})
});
...
对于 ejs 文件
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Type 1</th>
<th scope="col">Type 2</th>
<th scope="col">Evolution Level</th>
<th scope="col">Delete</th>
<th scope="col">Update</th>
</tr>
</thead>
<tbody>
<% listResults.forEach(function (pokemon) { %>
<tr>
<th scope="row"><%= pokemon.pokemon_id %></th>
<td><%= pokemon.pokemon_name %></td>
<td><%= pokemon.type1 %></td>
<td><%= pokemon.type2 %></td>
<td><%= pokemon.evLevel %></td>
<td><button class="btn btn-sm btn-danger">Delete</button></td>
<td><a class="btn btn-sm btn-success" href="#" role="button">Update</a></td>
</tr>
<% }) %>
</tbody>
</table>
当我尝试访问该页面时,出现错误,提示“listResults 未定义”,引用了 .forEach 行。
最佳答案
我不习惯 EJS,我通常使用 Handlebars 作为模板引擎,但由于您在 Express 中将数据作为名为 list 的对象传递:
res.render('listResults', list);
您尝试过list.listResults吗?
<% list.listResults.forEach(function (pokemon) { %>
<tr>
<th scope="row"><%= pokemon.pokemon_id %></th>
<td><%= pokemon.pokemon_name %></td>
<td><%= pokemon.type1 %></td>
<td><%= pokemon.type2 %></td>
<td><%= pokemon.evLevel %></td>
<td><button class="btn btn-sm btn-danger">Delete</button></td>
<td><a class="btn btn-sm btn-success" href="#" role="button">Update</a></td>
</tr>
<% }) %>
关于javascript - 使用node.js ejsexpress显示mysql查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50497907/