我能够在“knex-pracice”(我的 postgreql db)与 KNEX 之间建立连接,但是当我尝试使用我的 knex 实例进行查询时,我收到错误:“未处理的连接错误:角色“19016”不存在”。 19016是我的WINDOWS 10系统用户帐户的名称。我试图弄清楚为什么它使用“19016”而不是指定的用户“dunder-mifflin”。我对 postgres 和 knex 都很陌生,所以如果我的描述有点令人困惑或者我完全误解了我的问题,请原谅我。
此外,我尝试通过在数据库上创建名为“19016”的用户并尝试以这种方式连接来“破解”我的问题,但它只是给了我另一个错误:“未处理的连接错误:数据库“19016”不存在”。完全困惑如何让它使用用户名“dunder-mifflin”连接到 postgresql 不过,我可以通过我的 powershell 连接并查询数据库,没有任何问题......
.env
NODE_ENV=development
PORT=8000
DB_URL="postgresql://dunder-mifflin@localhost/knex-practice"
练习.js
//adds .env file for environment variable access
require('dotenv').config()
const knex = require('knex')
// database connection --> this connction comes from the .env file
const knexInstance = knex({
client: 'pg',
// database connection established --> environment variable comes from .env
// file
connection: process.env.DB_URL
})
console.log('connection successful');
// SQL query
knexInstance
.from('amazong_products')
.select('*')
.then(result => {
console.log(result)
});
package.json
{
"name": "knex-practice",
"version": "1.0.0",
"description": "knex-practice",
"main": "index.js",
"scripts": {
"test": "mocha --require test/setup.js",
"dev": "nodemon src/server.js",
"start": "node src/practice.js",
"predeploy": "npm audit",
"deploy": "git push heroku master"
},
"repository": {
"type": "git",
"url": "git+https://github.com/quonn-bernard/Express-Boilerplate.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/quonn-bernard/Express-Boilerplate/issues"
},
"homepage": "https://github.com/quonn-bernard/Express-Boilerplate#readme",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^7.0.0",
"express": "^4.16.4",
"helmet": "^3.16.0",
"knex": "^0.16.5",
"morgan": "^1.9.1",
"pg": "^7.9.0"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^6.0.2",
"nodemon": "^1.18.10",
"supertest": "^4.0.2"
}
}
最佳答案
您需要更改您的connection string至:
postgres://user:pass@localhost:5432/dbname
关于node.js - Knex 实例无法连接到 PostgreSQL DB : Unhandled rejection Error: role "19016" doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668271/