Node.js+Express Generator下HBS页面无法显示MySQL记录(无报错无输出)
代码问题排查与修正
核心逻辑错误点
- 路由逻辑错位
查询数据库的代码从未被实际执行:你把查询逻辑写在了router.post('/')路由下,但访问首页时触发的是GET请求对应的router.get('/'),既没有POST请求触发查询代码,就算查询被触发,回调里也没有将查询结果传给模板、没有结束响应的逻辑,会造成请求挂起。 - 模板循环语法不完整
{{#each}}块必须指定要遍历的数组参数,你写的{{#each}}后没有传任何数据源,就算路由拿到了查询结果,HBS也无法渲染循环内容。 - 数据库查询回调参数错位
mysql模块的查询回调参数顺序固定为(错误对象, 查询结果数组, 字段信息列表),你写的回调参数顺序虽然不影响当前的报错表现,但后续取值时会出现字段和数据混淆的问题。 - HTML结构嵌套错误
模板里的</thead>闭合标签错放在了</tbody>的后面,会导致表格解析异常。 - 冗余代码
第一行导入的const { response } = require('express');在整个文件里从未被调用,属于无意义的冗余代码。
修正后的核心代码
路由文件(routes/index.js)
var express = require('express'); var router = express.Router(); var mysql = require('mysql') // 数据库连接配置 var conn = mysql.createConnection({ host: 'localhost', user: 'root', password: 'MyDatabaseforMyProjects@', database: 'crud_db' }) // 数据库连接校验 conn.query('SELECT 1 + 1 AS solution', function (err) { if (err) throw err console.log('Connected to MySQL..') }) /* GET 首页路由:查询数据后传给模板渲染 */ router.get('/', function(req, res, next) { // 直接在首页GET路由中查询用户表数据 conn.query('SELECT * FROM user_form', function (err, userList) { if (err) throw err; // 把查询到的用户列表传给HBS模板 res.render('index', { userList: userList }); }) }); // 注册页GET路由 router.get('/create', function(req, res, next) { res.render('create'); }); // 提交注册POST路由 router.post('/create', function(req, res, next) { let data = { first_name: req.body.first_name, last_name: req.body.last_name, email : req.body.email, password: req.body.password, phone: req.body.phone, }; conn.query('INSERT INTO user_form set ?', [data], function(err) { if(err) { console.log(err) } else { return res.redirect('/'); } }) }); module.exports = router;
页面模板(views/index.hbs)
<h3 class="text-center border border-light p-5 container col-sm-5">User's Record</h3> <div class=" container col-sm-6"> Click <a href="/create">here</a> to Register user</div> <table class="table container col-sm-8"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">First name</th> <th scope="col">Last name</th> <th scope="col">Email</th> <th scope="col">Password</th> <th scope="col">Phone</th> <th scope="col">Action</th> </tr> </thead> <tbody> <!-- 指定遍历从路由传进来的userList数组 --> {{#each userList}} <tr> <td scope="col">{{ id }}</td> <td scope="col">{{ first_name }}</td> <td scope="col">{{ last_name }}</td> <td scope="col">{{ email }}</td> <td scope="col">{{ password }}</td> <td scope="col">{{ phone }}</td> </tr> {{/each}} </tbody> </table>
额外注意点
- 可以删除原来写的无触发场景的
router.post('/')逻辑,注册完成后重定向回首页时,会自动触发首页的GET查询逻辑,拿到最新数据渲染页面。 - 后续可以在查询逻辑里增加错误判断分支,出错时返回带错误提示的页面,避免直接抛出异常导致整个服务崩溃。
内容的提问来源于stack exchange,提问作者Asad A. Mirza
相关产品推荐
相关产品推荐

