Node.js 使用异步将信息从psql传递到ejs
我想用pg从一个PSQL数据库中提取信息,并将其显示到一个表中。我已经能够使用Promissions和async提取数据并将其显示为对象(“所有数据都显示在我下面用来测试的端点上”),但无法确定如何将其发送到EJS进行渲染Node.js 使用异步将信息从psql传递到ejs,node.js,ejs,Node.js,Ejs,我想用pg从一个PSQL数据库中提取信息,并将其显示到一个表中。我已经能够使用Promissions和async提取数据并将其显示为对象(“所有数据都显示在我下面用来测试的端点上”),但无法确定如何将其发送到EJS进行渲染 //using async/await router.route('/') .get(async function (req, res) { try { let accountList = await createA
//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未定义”错误
我做错了什么?在将函数发送到渲染之前,我使用了这里的结构来调用该函数,该函数成功了。我觉得这和异步代码有关,让我感到沮丧的是,它花了我这么长时间
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'})
})
});
当你进入主页时,你能在浏览器中看到视图的内容吗?您是否设置了视图
app.set('views',path)
是的,视图设置如上所述。我无法将数据发送到主页,但我可以将其发送到仅删除定义app.get('/')
的最后3行代码。这一行用于索引页,然后将app.use('/accountlist'
替换为app.use('/')