【问题标题】:Pass variable from app.get to pug view将变量从 app.get 传递到 pug 视图
【发布时间】:2019-01-15 09:42:34
【问题描述】:

我有以下代码调用我的数据库并下拉信息

    // 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]

【问题讨论】:

    标签: node.js api express variables pug


    【解决方案1】:

    首先,您不应该在 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
    

    【讨论】:

    • 这是我得到的最好的答案 - 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2020-04-16
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2021-12-31
    • 2020-07-04
    相关资源
    最近更新 更多