【问题标题】:How do I make my own CRUD module using node-postgres?如何使用 node-postgres 制作自己的 CRUD 模块?
【发布时间】:2019-06-10 12:03:33
【问题描述】:

当对 NodeJS 服务器(不是本地主机)进行 ajax 调用时,它不会返回任何内容。在进行 ajax 调用时,NodeJS 在我的 NodeJS 控制台 (ssh) 中显示结果。 NodeJS 在 ajax 调用后 10-15 秒崩溃并出现错误。

我尝试过使用 Pool 但我不明白。

前端

"use strict";
var btn = document.getElementById('button');

function ajax(){
  let req = new XMLHttpRequest();
  req.onreadystatechange = function(){
    if( this.readyState === 4 && this.status === 200){
      let data = JSON.parse( this.responseText );
      console.log(data);
    }
  };
  req.open("GET", "/ajax/", true);
  req.send();
};

btn.addEventListener("click", (e)=>{
  e.preventDefault();
  ajax();
});

后端(nodejs)

const {Client} = require('pg');

const db = new Client({
  user: "x",
  password: "x",
  host: "x",
  port: 123,
  database: "abc",
  ssl: true
});

module.exports = {
  async select( sql ){
    try{
      await db.connect();
      console.log("Connected to DB");
      const result = await db.query( sql );
      console.table(result.rows); // <-- Shows the data i want to send back.
      return JSON.stringify(result.rows);
    }

    catch(ex){
      console.log("We messed up! " + ex);
    }

    finally{
      await db.end();
      console.log("DB connection closed");
    }
  }
};

我希望 ajax 调用从 postgres 数据库返回数据。我在 nodeJS 控制台中看到的相同数据。

Error: Client has already been connected. You cannot reuse a client.
events.js:177
      throw er; // Unhandled 'error' event
      ^

Error: This socket has been ended by the other party
    at TLSSocket.writeAfterFIN [as write] (net.js:407:14)
    at Connection.end 
 code: 'EPIPE'

【问题讨论】:

    标签: javascript node.js asynchronous node-postgres


    【解决方案1】:

    要使用pg 模块中的Client,您必须为每个数据库查询创建一个新的Client 实例,因为每个客户端代表不同的用户和连接。因此,您应该将它们视为一次性使用实例:

    const {Client} = require('pg');
    const dbConn = {
      user: "x",
      password: "x",
      host: "x",
      port: 123,
      database: "abc",
      ssl: true
    };
    
    module.exports = {
      async select( sql ){
        const db = new Client(dbConn); // <-- Create new Client for every call
    
        try{
          await db.connect();
          console.log("Connected to DB");
          const result = await db.query( sql );
          console.table(result.rows); // <-- Shows the data i want to send back.
          return JSON.stringify(result.rows);
        }
    
        catch(ex){
          console.log("We messed up! " + ex);
        }
    
        finally{
          await db.end();
          console.log("DB connection closed");
        }
      }
    };
    

    在您的情况下,也为recommended in the documentation,您需要Pool。它与Client 基本相同,只是现在 Pool 将在内部为您管理客户端。

    从您的角度来看,它实际上与 Client 并没有太大区别,只是它更简单。

    const {Pool} = require('pg');
    
    // Notice here
    const db = new Pool({
      user: "x",
      password: "x",
      host: "x",
      port: 123,
      database: "abc",
      ssl: true
    });
    
    module.exports = {
      async select( sql ){
        try
          const result = await pool.query( sql ); // <-- Notice here
          console.table(result.rows); // <-- Shows the data i want to send back.
          return JSON.stringify(result.rows);
        }
    
        catch(ex){
          console.log("We messed up! " + ex);
        }
    
        /* No need to release client as Pool does it for you internally */
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多