【发布时间】:2021-03-27 13:08:59
【问题描述】:
我无法在 HTML 页面上显示 MySQL 表数据。现在,我正在使用带有 EJS 模板引擎的 Express 框架。
我有app.js 主文件和index.ejs 文件(在views 文件夹上)。
我有一个简单的表,名称为:表单和两个字段(名称、用户名)。
运行应用程序时,请参阅以下错误:
TypeError: C:\Users\azeri\Desktop\NODE-COURSE\node-form\views\index.ejs:11
9| </thead>
10| <tbody>
>> 11| <% obj.forEach(function(user){ %>
12| <tr>
13| <td><%= user.name %></td>
14| <td><%= user.username %></td>
obj.forEach is not a function
at eval (C:\Users\azeri\Desktop\NODE-COURSE\node-form\views\index.ejs:10:12)
at index (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\ejs\lib\ejs.js:691:17)
at tryHandleCache (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\ejs\lib\ejs.js:272:36)
at View.exports.renderFile [as engine] (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\ejs\lib\ejs.js:489:10)
at View.render (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\express\lib\response.js:1012:7)
at Query.<anonymous> (C:\Users\azeri\Desktop\NODE-COURSE\node-form\app.js:23:11)
at Query.<anonymous> (C:\Users\azeri\Desktop\NODE-COURSE\node-form\node_modules\mysql\lib\Connection.js:526:10)
app.js 文件
var express = require('express');
var app = express();
var path = require('path');
var mysql = require('mysql');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "nodeform"
});
var obj = {};
app.get('', function(req, res){
con.query("SELECT * FROM form", function (err, result) {
if (err) throw err;
else {
obj = {print: result};
res.render('index', {obj: obj});
}
});
});
app.listen(3000);
console.log("Running at Port 3000");
index.ejs 文件
<html>
<body>
<table id="table">
<thead>
<tr>
<th>Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<% obj.forEach(function(user){ %>
<tr>
<td><%= user.name %></td>
<td><%= user.username %></td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
【问题讨论】: