我正在用node和sequelize开发一个后端应用程序。我的数据库来自postgresql。
启动应用程序时,数据库连接工作正常,但是当它尝试与数据库进行通信以读取或更新时,它会失败并显示连接错误: 用户“ wushin”的密码身份验证失败。
我似乎真的很奇怪,因为数据库连接已经完成,并且密码已经过验证。你们知道发生了什么吗? pg模块也许有问题,但是我尝试了不同的版本。
版本 节点:10.17.0 续集:5.21.3 邮编:10.11 pg模块:7.17.1
->此代码可以正常工作:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
->但是此承诺因SequelizeConnectionError而失败:
models.Question.findAll()
.then(data => {
console.log('-> Succeeded data fetching\n')
console.log(data)
})
.catch(err => {
console.log('-> Failed data fetching\n')
console.log('Error', err)
})
日志:
yarn run v1.19.2
$ node index.js
Example app listening on port 4000 or something!
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
- Trying to fetch data:
-> Failed data fetching
Error:
{ SequelizeConnectionError: password authentication failed for user "wushin"
at connection.connect.err (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:182:24)
at Connection.connectingErrorHandler (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/client.js:194:14)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (/home/wushin/Projects/GuessGame/theguessgame-api/node_modules/pg/lib/connection.js:128:12)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:287:12)
at readableAddChunk (_stream_readable.js:268:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'SequelizeConnectionError'
答案 0 :(得分:0)
似乎您没有向主机传递任何配置给Sequelize
。最低配置为主机,端口,数据库名称,方言用户名和密码。
从文档中
const Sequelize = require('sequelize'); // Option 1: Passing parameters separately const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ }); // Option 2: Passing a connection URI const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
答案 1 :(得分:0)
我终于解决了这个问题。问题在于使用sequelize,要求模型使用sequelize创建的配置存储库,调用应该为您进行sequelize连接的index.js。
我与sequelize的连接运行良好,但是由于需要模型而启动的连接在我的数据库中有一些不良信息。
因此,我无法使用导入的模型来获取数据库上的数据。
我插入了很好的配置信息:
require('dotenv').config()
module.exports = {
development: {
url: process.env.DATABASE_URL,
dialect: 'postgres',
},
test: {
url: process.env.DATABASE_TEST_URL,
dialect: 'postgres',
},
production: {
url: process.env.DATABASE_PROD_URL,
dialect: 'postgres',
},
}
并完全删除了我自己写的那一行:
const sequelize = new Sequelize(process.env.DATABASE_DEV_URL)
现在是models / index.js通过以下方式连接到数据库:
const sequelize = new Sequelize(process.env.DATABASE_URL)
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.\n')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})