如何在Heroku上的现有NodeJS项目中添加PostgreSQL数据库?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (97)

正在尝试将一个PostgreSQL数据库添加到我在heroku上的现有nodejs项目中。无法访问本地数据库版本,也无法写入到heroku数据库。这是我尝试过的代码的一部分:

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

const client = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: true,
});

client.connect();

// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X

client.query(qu, (err, res) => {
  //console.log("trying");
  if (err) throw err;
  for (let row of res.rows) {
    console.log(JSON.stringify(row));
  }
  client.end();
});

但我无法访问本地数据库或对远程数据库执行任何操作。

这是本地错误消息:

(node:8402) UnhandledPromiseRejectionWarning: error: password authentication failed for user "..." at Connection.parseE (.../theland/node_modules/pg/lib/connection.js:553:11) at Connection.parseMessage (.../theland/node_modules/pg/lib/connection.js:378:19) at TLSSocket. (.../theland/node_modules/pg/lib/connection.js:119:22) at emitOne (events.js:116:13) at TLSSocket.emit (events.js:211:7) at addChunk (_stream_readable.js:263:12) at readableAddChunk (_stream_readable.js:250:11) at TLSSocket.Readable.push (_stream_readable.js:208:10) at TLSWrap.onread (net.js:597:20) (node:8402) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:8402) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

提问于
用户回答回答于

用户“...”的密码验证失败

显然没有为用户使用正确的密码但有一台服务器响应请求。

未处理的承诺拒绝

有一个错误,可能是在这里抛出:

if (err) throw err;

尝试把它放入一些try-catch-block,例如

function queryDatabase() {
  try {
    const client = new Client({
      connectionString: process.env.DATABASE_URL,
      ssl: true,
    });

    client.connect();

    // client
    let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
    //qu = 'CREATE TABLE test (name varchar(40));';
    //qu = 'SELECT * FROM test;';
    // qu = 'INSERT INTO test name VALUES("testasdf");';
    // qu = 'CREATE DATABASE X

    client.query(qu, (err, res) => {
      //console.log("trying");
      if (err) throw err;
      for (let row of res.rows) {
        console.log(JSON.stringify(row));
      }
      client.end();
    });
  } catch (error) {
    // if you need further help, remember to provide this error here.
    console.log(error);
  }
}

扫码关注云+社区

领取腾讯云代金券