【问题标题】:Returning a Postgres query in Node, server won't run在 Node 中返回 Postgres 查询,服务器不会运行
【发布时间】:2019-08-02 20:49:28
【问题描述】:

我制作了一个简单的 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 ] }

【问题讨论】:

    标签: javascript node.js database server


    【解决方案1】:

    希望我的项目能给你一些想法。

    在 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();

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 2022-11-05
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      相关资源
      最近更新 更多