【问题标题】:printing postgres data to html with node.js使用 node.js 将 postgres 数据打印到 html
【发布时间】:2015-03-13 10:14:02
【问题描述】:

我正在尝试从 pg 数据库中打印出一些用户。在 index.js 文件中,我有以下内容:

function list(callback) {
pg.connect(cstr, function(err, client, done) {
        if (err) {
            callback(err);
        } else {
            client.query('select fname from users', function(err, result) {
                // Ends the "transaction":
                done();
                // Disconnects from the database:
                client.end();
                if (err) {
                    callback(err);
                } else {
                    callback(result.rows);
                }
            });
        }
    });
}

在我的 app.js 中,我有以下内容:

app.get('/users', function (req, res) {

  db.list(function(data){ 
    console.log(data); 
    res.send(data); 
  }); 

});

我知道它会吸引用户,因为它将它输出到控制台。但是当我重新加载页面时,我得到“没有收到数据”。

console.log 输出以下内容:

[ { fname: 'Frank' },
  { fname: 'Jake' },
  { fname: 'Cristiano' },
  { fname: 'Lionel' },
  { fname: 'Wayne' } ]

我需要在浏览器上以表格形式输出它,但我不知道如何让它发送数据。

【问题讨论】:

    标签: javascript html node.js postgresql


    【解决方案1】:

    你可以试试 -

    db.list(function(data){ console.log(data); res.setHeader('content-type', 'application/json'); res.end(data); });

    另外,当您将数据发送到 html 时,您需要使用一些 javascript 模板引擎,如 ejs 来在 html 中呈现数据。

    更多关于 ejs 的信息是here

    希望对您有所帮助。

    谢谢

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2018-03-03
      相关资源
      最近更新 更多