在select的数据上使用MySQL + Node.js + Jade发行
错误
问题:无法读取jade_debug.unshift.lineno(在(C:\ Users \ Dev \ Node_js \ node_modules \ jade \ lib \ jade.js:160:8),:111:31)处的未定义属性“长度” eval(eval at(C:\ Users \ Dev \ Node_js \ node_modules \ jade \ lib \ jade.js:160:8),
DBfunction
exports.selectRows = function(){ var objBD = BD(); objBD.query('SELECT * FROM usr ', function(results) { return(results); }); }
路线
exports.index = function(req, res) { res.render('customer/index',{ customers: db.selectRows() }); };
index.jade
each item in customers tr td a(href='/customer/details/#{item.id}') #{item.id} td #{item.name} td #{item.email} td #{item.phone}
你的代码的问题在于selectRows
方法是asynchronous执行的,你的handler方法中的selectRows
db.selectRows()
expression式总是返回undefined
值,因此execption( customers
模板variables是undefined
)。
您应该将以下更改添加到您的代码,以使其正常工作:
数据库function:
exports.selectRows = function(callback){ var objBD = BD(); objBD.query('SELECT * FROM usr ', callback); }
路线:
exports.index = function(req, res) { db.selectRows(function(results){ res.render('customer/index', { customers: results }); }); }
有时你可能有一个情况(很常见的Node.js模式),你的callback
有两个参数:
- 首先会是一个错误 – 如果数据库查询成功,应该是
undefined
- 其次是数据库查询结果数据
在两个参数(错误和结果)的情况下,您的路线应如下所示:
exports.index = function(req, res) { db.selectRows(function(err, results){ if (err) return res.send(500, "DB QUERY ERROR"); res.render('customer/index', { customers: results }); }); }
你也可以简化你的index.jade
each item in customers tr td: a(href='/customer/details/#{item.id}')= item.id td= item.name td= item.email td= item.phone
我希望这会有所帮助。