将变量从 app.get 传递到哈巴狗视图
Pass variable from app.get to pug view
我有以下代码调用我的数据库并提取信息
// GET the number of apples left in stock
app.get('/apples', function (req, res) {
sql.connect(config, function() {
var request = new sql.Request();
request.query("select quantity from table WHERE type = 'apple'", function(err, recordset) {
var arrayLength = recordset.length;
for (var i = 0; i < arrayLength; i++) {
console.log(recordset[i]["quantity"]);
res.render('index', {results: recordset});
};
});
})
})
这非常有效.. 当我浏览到它时,它会将我发送到索引页面,然后我可以在我的控制台日志中看到来自数据库的值
在我的 index.pug 然后我有这个
h3(align='middle') #{results}
在索引页上我只看到这个 [object Object]
首先,您不应该在 for 循环中多次调用 res.render
。
app.get('/apples', function (req, res) {
sql.connect(config, function () {
var request = new sql.Request();
request.query("select quantity from table WHERE type = 'apple'", function (err, recordset) {
var arrayLength = recordset.length;
for (var i = 0; i < arrayLength; i++) {
console.log(recordset[i]["quantity"]);
};
res.render('index', { results: recordset });
});
});
});
那么你应该在你的 pug 文件中使用 each
来迭代结果集。
更多迭代文档:https://pugjs.org/language/iteration.html
each val in results
h3(align='middle')=val.quantity
我有以下代码调用我的数据库并提取信息
// GET the number of apples left in stock
app.get('/apples', function (req, res) {
sql.connect(config, function() {
var request = new sql.Request();
request.query("select quantity from table WHERE type = 'apple'", function(err, recordset) {
var arrayLength = recordset.length;
for (var i = 0; i < arrayLength; i++) {
console.log(recordset[i]["quantity"]);
res.render('index', {results: recordset});
};
});
})
})
这非常有效.. 当我浏览到它时,它会将我发送到索引页面,然后我可以在我的控制台日志中看到来自数据库的值
在我的 index.pug 然后我有这个
h3(align='middle') #{results}
在索引页上我只看到这个 [object Object]
首先,您不应该在 for 循环中多次调用 res.render
。
app.get('/apples', function (req, res) {
sql.connect(config, function () {
var request = new sql.Request();
request.query("select quantity from table WHERE type = 'apple'", function (err, recordset) {
var arrayLength = recordset.length;
for (var i = 0; i < arrayLength; i++) {
console.log(recordset[i]["quantity"]);
};
res.render('index', { results: recordset });
});
});
});
那么你应该在你的 pug 文件中使用 each
来迭代结果集。
更多迭代文档:https://pugjs.org/language/iteration.html
each val in results
h3(align='middle')=val.quantity