【问题标题】:Getting [object Object] when I try to display SQL query results in Jade当我尝试在 Jade 中显示 SQL 查询结果时获取 [object Object]
【发布时间】:2013-02-14 18:34:09
【问题描述】:

我刚开始使用 Node.js,我完全不明白为什么我的 SQL 查询结果无法呈现在页面上。

connection.query('SELECT * FROM testTable', function selectCb(err, rows, fields) {
  if (err) {
    throw err;
  }
  for (var i in rows) {
      console.log(rows[i]);
  }
  res.render('showResults.jade', {
    results: rows
  });
});

结果完美地显示在控制台中,但是当我尝试使用 Jade 渲染它们时,我得到了一些项目符号(等于表中的条目数),但每个项目符号后跟 [object, Object] .这是我的 Jade 文件:

h1 SQL Results are as follows:
ul
  each item, i in results
    li= item

是否需要额外的步骤或其他操作才能使结果正确显示?

【问题讨论】:

    标签: node.js pug


    【解决方案1】:

    您看到的输出是因为 Jade 只是在表达式的结果上调用 .toString()。而且,对于Objects,比如itemthat's the default result

    > {}.toString()
    '[object Object]'
    

    要获得更有用的东西,您必须指定格式:

    li #{item.prop1} (#{item.prop2})
    

    对于 JSON:

    li= JSON.stringify(item)
    

    如果您想要使用console.log() 看到的格式,可以将函数it usesutil.inspect() 公开为视图助手:

    // Express 3
    app.locals.inspect = require('util').inspect;
    
    li= inspect(item)
    

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 2023-02-23
      • 2021-01-12
      • 2018-04-28
      • 1970-01-01
      • 2020-06-02
      • 2013-06-25
      • 1970-01-01
      • 2017-12-15
      相关资源
      最近更新 更多