如何使用node-postgres制作自己的CRUD模块?

时间:2019-06-10 03:42:43

标签: javascript node.js asynchronous node-postgres

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

我尝试使用Pool,但我不理解。

前端

vif_cal(input_data=dataset[['a','b','c']], dependent_col='d')

后端(nodejs)

"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();
});

我希望ajax调用从postgres数据库返回数据。我在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");
    }
  }
};

1 个答案:

答案 0 :(得分:1)

要使用Client模块中的pg,必须为每个数据库查询创建一个新的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 */
  }
};