How to render postgresql results in ejs using node pg?

て烟熏妆下的殇ゞ 提交于 2019-12-25 01:12:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!