[英]Trying to run express node js as https server but it won't run
[英]Returning a Postgres query in Node, server won't run
我制作了一個托管本地服務器的簡單JS文件,然后使用Node讀取數據庫並返回結果。 我的目的是創建一個僅返回行的頁面,然后再創建新頁面。
問題是控制台記錄了結果,但服務器未連接。 我可以制作僅托管服務器的文件,但是放入查詢會使服務器無法運行。 如何使查詢在服務器上運行?
這是代碼:
const pg = require("pg");
const pool = new pg.Pool({
user: "James",
host: "127.0.0.1",
database: "makersBnb",
password: "",
port: "5432"});
pool.query('SELECT * FROM listings', (err, res) => {
console.log(err, res);
pool.end();
});
該表有2行。 這是控制台:
Result {
command: 'SELECT',
rowCount: 2,
oid: null,
rows:
[ { id: 2,
listing_name: 'testListing',
price: '5',
description: 'description',
owner_name: 'me',
email: 'private@email.com',
phone_num: '07777777771' },
{ id: 1,
listing_name: 'a',
price: 'b',
description: 'c',
owner_name: 'd',
email: 'e',
phone_num: 'f' } ],
_parsers:
[ [Function: parseInteger],
[Function: noParse],
[Function: noParse],
[Function: noParse],
[Function: noParse],
[Function: noParse],
[Function: noParse] ],
RowCtor: null,
rowAsArray: false,
_getTypeParser: [Function: bound ] }
希望我的項目能給您一些想法。
在postgreSQL文件中:
const {Pool} = require('pg');
const config = require('../config');
const postgre = config.postgre;
const pool = new Pool(postgre);
module.exports = {
getList: (/* could add params here */ callback) => {
let param = []; //if there is params add to here in sequence,
// for text using let param = [email]
let query = 'select * from listings;'
// text is sample using params;
let text = 'select * from users where email=$1';
return pool.query(text, param, callback)
},
// here you can add more functions as you like.
}
在app.js中
const db = require('/postgresql') //import the file abave
app.get('/getList',(req,res)=>{
db.getList((err,messageFromDB)=>{
if (err) {
console.log(err);
} else {
res.send(messageFromDB.rows);
}
})
}
這將使您每次調用/ getList並且數據庫(node.js服務器)返回結果。 或者您可以簡單地console.log結果或執行其他操作。
更新:在查看我的答案並查看您的問題時,您不應調用pool.end();
如果您希望服務器繼續運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.