【发布时间】: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('/')