问题
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) }) }
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
}
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
});
});
Then rendering in an EJS file:
<body>
<div><h1>Hello World</h1></div>
<div><%= todoDbList %> </div>
</body>
What am I missing here to see the query results in the div and not the query itself?
回答1:
Answering my own question in case someone else has a similar question.
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})
})
};
Call the function in the app.js file
//all todo information
app.get('/todos', db.getAllItems);
来源:https://stackoverflow.com/questions/59277144/how-to-render-postgresql-results-in-ejs-using-node-pg