如何使用节点pg在ejs中渲染postgresql结果? [英] How to render postgresql results in ejs using node pg?
问题描述
我是node / express / postgres的新手,正在尝试构建一个简单的待办事项应用程序。我正在尝试使用ejs文件渲染视图,但是页面没有显示查询结果,而是显示查询本身:
I'm new to node/express/postgres and trying to build a simple todo application. I'm trying to render a view using an ejs file, but instead of displaying the query results, the page is displaying the query itself:
(request, response) => { pool.query('SELECT * FROM items ORDER BY id ASC', (error, results) => { if (error) { throw error } response.status(200).json(results.rows) }) }
我正在使用querys.js文件生成查询:
I'm generating the queries in a queries.js file:
const Pool = require('pg').Pool
const pool = new Pool({
user: '*',
host: 'localhost',
database: 'todo',
password: '*',
port: 5432,
})
const getAllItems = (request, response) => {
pool.query('SELECT * FROM items ORDER BY id ASC', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
module.exports = {
getAllItems
}
并在app.js文件中调用它:
And calling it in the app.js file:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
const db = require('./queries');
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
var todoDbList = db.getAllItems;
var itemNames = db.getAllItemNames;
//All todo information
app.get('/items',function(req, res) {
res.render("allItemInfo.ejs", {
todoDbList: db.getAllItems
});
});
然后在EJS文件中渲染:
Then rendering in an EJS file:
<body>
<div><h1>Hello World</h1></div>
<div><%= todoDbList %> </div>
</body>
我在这里想看到div中的查询结果而不是查询本身时想念什么?
What am I missing here to see the query results in the div and not the query itself?
推荐答案
回答我自己的问题,以防其他人有类似的问题。
Answering my own question in case someone else has a similar question.
在querys.js文件中重新配置getAllItems函数以呈现.ejs文件并传递查询结果
Reconfigured the getAllItems function in the queries.js file to render the .ejs file and pass in the query results
const getAllItems = function(req, res) {
const sql = 'SELECT * FROM items ORDER BY id ASC';
pool.query(sql, (error, results) => {
if (error) {
throw error;
}
res.render("allItemInfo.ejs", {todoDbList: results.rows})
})
};
调用app.js文件中的函数
Call the function in the app.js file
//all todo information
app.get('/todos', db.getAllItems);
这篇关于如何使用节点pg在ejs中渲染postgresql结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!