javascript - 在 Node 中返回 Postgres 查询,服务器将无法运行

标签 javascript node.js database server

我制作了一个简单的 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();

关于javascript - 在 Node 中返回 Postgres 查询,服务器将无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55120502/

相关文章:

javascript - 如何在 e4x 中添加另一个同级元素?

javascript - 在输入类型的文本中,为什么我无法添加 - 在键入四个字母后使用 javascript?

node.js - 使用 Mognodb 和 Node.js 聚合函数返回空白数组值

sql - Oracle 12c - CLOB 字段中的西里尔字符

mysql - PostgreSQL 的 EXPLAIN ANALYZE 的 MySQL 等价物是什么

javascript - XMLHTTPRequest Level 2 和 CORS 服务器

node.js - 指示pm2不要在json文件中启动多个实例

javascript - 无法解析模块 "events"React-Native

php - 如何将 MySQL 数据库连接到 iPage 中的域?

javascript - 如何获取动态加载图像的图像加载?