【问题标题】:PG NPM Package Not Connecting to Localhost DBPG NPM 包未连接到 Localhost DB
【发布时间】:2016-08-03 02:17:10
【问题描述】:

我无法让pg 包在我的本地系统上运行。我尝试运行以下命令:

var pg = require('pg');
var con_string = "postgres://user:password@localhost:5432/documentation";

var client = new pg.Client();
client.connect(con_string, function(err, res) {
// stuff here
});

但我不断收到TypeError: callback is not a function

是否需要更改设置才能通过连接字符串连接到数据库?我已经在本地计算机上的数据库上尝试了上面user:password 中使用的用户名和密码,并且可以正常连接。

我也尝试过安装pg的项目目录中的node shell,但没有任何运气。

谢谢

这是我运行以下答案时得到的错误:

$ node pg_test.js 
error fetching client from pool { [error: password authentication failed for user "jake"]

【问题讨论】:

  • 不是很清楚的告诉你一个错误吗? “错误:用户“jake”的密码验证失败”
  • 我同意错误是明确的。我只是不明白为什么在命令行上运行时身份验证失败并显示连接字符串。
  • 因为您从 conn 字符串发送“密码”作为密码,而您在 psql -U jake -W -d documentation 此处没有发送任何密码。
  • 这是提示输入密码的标志。我想我可以尝试在没有提供密码的情况下查看它是否可以工作,然后提示我输入密码。下班后我得检查一下。
  • 我刚刚尝试了没有密码的连接字符串,它没有工作。这让我相信这与设置有关。

标签: javascript node.js postgresql npm


【解决方案1】:

直接来自https://github.com/brianc/node-postgres的文档:

var pg = require('pg');
var conString = "postgres://user:password@localhost:5432/documentation";

//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 10 (also configurable)
pg.connect(conString, function(err, client, done) {
  if(err) {
    return console.error('error fetching client from pool', err);
  }
  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
    //call `done()` to release the client back to the pool
    done();

    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].number);
    //output: 1
  });
});

【讨论】:

  • 我应该补充一点,我尝试将其复制并粘贴到我的项目目录中的脚本中为pg_test.js 然后我运行node pg_test.js 并打开浏览器不幸看到error fetching content from pool...
  • 因为您的登录名/密码不正确 - postgres 的默认用户:postgres。此代码有效。检查连接字符串。尝试通过 postgres 客户端等连接。
  • 连接字符串适用于postgres 用户,但我可以确保我使用的用户密码可以用于psql -U jake -W -d documentation,但它不起作用。
猜你喜欢
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 2022-12-21
  • 2021-12-15
  • 2019-09-08
相关资源
最近更新 更多