【发布时间】:2019-11-18 15:06:29
【问题描述】:
我用这个命令在postgresql 创建了一个用户:
createuser --interactive
但它并没有要求输入新密码,所以我认为密码设置为我计算机的 sudo 密码。但是,当我尝试使用以下代码连接到我的数据库时:
async function connect() {
let connection_string = "postgres://[username]:[password]@localhost:5432/[database]"
let client = new pg.Client(connection_string)
await client.connect()
let query = await client.query("select * from Messages;")
query.rows.forEach(row => {
console.log(row)
})
await client.end()
}
我收到了这个错误:
(node:7106) UnhandledPromiseRejectionWarning: error: password authentication failed for user "[username]"
我该如何解决?
【问题讨论】:
-
仅供参考,如果传递给
new pg.Client()(即上述变量中的connection_string)的参数是错误的URL,那么无论如何你都会得到同样的错误。例如new pg.Client(undefined)也会给出错误error: password authentication failed for user <username>。似乎提供更有用的错误消息是个好主意,因为这对我来说非常具有误导性。 -
如果您使用的是
node.jsdotenv和pg,请确保您的index.js中有require('dotenv').config();。添加后,此错误已修复。
标签: postgresql javascript node.js postgresql