【问题标题】:Passing info from psql to ejs using async使用异步将信息从 psql 传递到 ejs
【发布时间】:2020-10-12 15:26:56
【问题描述】:

我想用 pg 从 PSQL 数据库中提取信息并将信息显示到表中。我已经能够使用 Promise 和异步提取数据并显示为一个对象(?所有数据都显示在我下面用来测试的端点),但无法弄清楚如何将其发送到 EJS 进行渲染。

//using async/await
router.route('/')
    .get(async function (req, res) {      
        try {
            let accountList = await createALb();
            res.send(accountList);
            //res.render('/accountList', {'accountList': accountList})
        }
        catch(err) {
            res.status(500).send(err)
        }
    });


async function createALb() {
    const client = await pool.connect()
    const data = await client.query(select)
    client.release()
    //console.log(data) - this is returning the object, it's working homie
    return data
    
}
   
module.exports = router;

server.js

const accountList = require('./pgpooling');
//const accountList = require('./accountList.json'); - I can access this info and manipulate into a table

//setup view engine
app.engine("ejs", ejsEngine);
app.set("view engine", "ejs");

//this is sending the right information
app.use('/accountList', accountList)

app.get('/', (req, res) => {
   res.render("ejs/index");
});

任何时候我尝试在 EJS 中访问:

<%- accountList.rows[0].account_name %>

或类似的,它会抛出“accountList is not defined”错误。

我做错了什么?

【问题讨论】:

  • 进入首页时,能在浏览器中看到视图的内容吗?你设置了视图app.set('views', path)
  • 是的,视图设置如上。我无法将数据发送到主页,但我可以将其发送到localhost:3000/accountList
  • 只删除定义app.get('/')的最后3行代码,这是索引页,然后将app.use('/accoutList'替换为app.use('/')

标签: node.js ejs


【解决方案1】:

我在这里使用了NodeJS retrieve JSON and serve to EJS template 的结构来调用该函数,然后再将其发送到渲染器并且它起作用了。认为这与异步代码有关,令人沮丧的是我花了这么长时间

app.get('/', (req, res) => {
  accountList.createALb()
    .then(function(accountList){
      res.render("ejs/index", {
        'accountList': accountList})
    })
    .catch(function(err){
      res.status(500).send({error: 'we done homie'})
    })  
 });

【讨论】:

    猜你喜欢
    • 2017-05-23
    • 1970-01-01
    • 2012-12-19
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多