我正在编写代码,使用node.js和express-hbs在网页上打印一些用户信息
我试过这段代码
<!DOCTYPE html>
<html>
<head>
<title>Person List</title>
</head>
<body>
<table>
{{#each person}}
<tr>
<td>{{person.id}}
</td>
<td><a href='/person/'+person.id>{{person.firstname}}</a></td>
<td>{{person.GameId}}</td>
</tr>
{{/each}}
</table>
<td>{{person.firstname}}</td>
</body>
</html>
node.js代码
app.get('/usersrooms', function (req, res, next) {
var personList = [];
//var userslist = "SELECT * FROM users ORDER BY id";
connection.query('SELECT * FROM users ORDER BY id', function(err, rows, fields) {
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server error"});
} else {
// Loop check on each row
for (var i = 0; i < rows.length; i++) {
// Create an object to save current row's data
var person = {
'email':rows[i].email,
'firstname':rows[i].firstname,
'GameId':rows[i].GameId,
'id':rows[i].id
}
// Add object into array
personList.push(person);
}
res.render('index', {"personList": personList});
}
});
// Close the MySQL connection
connection.end();
});
但是当我运行它并且服务器断开连接并且我的网页上没有任何数据时出现此错误
throw er; // Unhandled 'error' event ^
错误:调用quit后无法将Quit排入队列。
答案 0 :(得分:4)
移除对connection.end();
请参阅this answer,其中解释了为什么只有在关闭应用程序时才应调用 connection.end()
关于HTML中缺少行,可能是因为当您将人员列表发送到personList
参数中的模板时,您正在迭代其中名为person
的数组。试试:
<!DOCTYPE html>
<html>
<head>
<title>Person List</title>
</head>
<body>
<table>
{{#each personList}}
<tr>
<td>{{id}}
</td>
<td><a href='/person/{{id}}'>{{firstname}}</a></td>
<td>{{GameId}}</td>
</tr>
{{/each}}
</table>
</body>
</html>
请注意,我删除了<td>{{person.firstname}}</td>
部分,因为我想要在那里显示firstname
答案 1 :(得分:0)
app.get('/usersrooms', function (req, res, next) {
var personList = [];
connection.query('SELECT * FROM users ORDER BY id', function (err, rows, fields) {
if (err) {
res.status(500).json({ "status_code": 500, "status_message": "internal server error" });
console.error(JSON.stringify(err));
//return here to prevent second res call
return;
} else {
// Loop check on each row
for (var i = 0; i < rows.length; i++) {
// Create an object to save current row's data
var person = {
'email': rows[i].email,
'firstname': rows[i].firstname,
'GameId': rows[i].GameId,
'id': rows[i].id
}
// Add object into array
personList.push(person);
}
res.render('index', { "personList": personList });
}
});
});