Postgresql 如何将knex.js连接到PostgresSQL数据库?

Postgresql 如何将knex.js连接到PostgresSQL数据库?,postgresql,knex.js,Postgresql,Knex.js,您好,我正在尝试使用Knex.js将数据库连接到server.js。我曾尝试将用户添加为postgresql,并尝试将主机添加为localhost,但这并没有起到作用。我总是得到一个 下面是我列出所有数据库的时候! 加载资源失败:服务器响应状态为400(错误请求) 下面是我尝试注册时的错误快照 下面是我的register.js,它应该有助于重新注册到数据库 下面是我的server.js文件 const express = require('express'); const bodyParse

您好,我正在尝试使用Knex.js将数据库连接到server.js。我曾尝试将用户添加为postgresql,并尝试将主机添加为localhost,但这并没有起到作用。我总是得到一个

下面是我列出所有数据库的时候!

加载资源失败:服务器响应状态为400(错误请求)

下面是我尝试注册时的错误快照

下面是我的register.js,它应该有助于重新注册到数据库

下面是我的server.js文件

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');

const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');

const db = knex({
  client: 'pg',
  connection: {
    host : 'localhost',
    user : 'postgres',
    database : 'smartbrain1'
  }
});

const app = express();

app.use(cors())
app.use(bodyParser.json());

app.get('/', (req, res)=> { res.send(db.users) })
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post('/register', (req, res) => { register.handleRegister(req, res, db, bcrypt) })
app.get('/profile/:id', (req, res) => { profile.handleProfileGet(req, res, db)})
app.put('/image', (req, res) => { image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => { image.handleApiCall(req, res)})

app.listen(3000, ()=> {
  console.log('app is running on port 3000');
}) 
这是我用postgreSQL在终端中创建的数据库,作为快照


您应该从编写独立节点应用程序开始,该应用程序连接pg并运行查询。然后,当您知道连接DB按预期工作时,就可以开始与应用程序的其他部分集成。现在这个问题有太多不相关的信息

首先尝试从shell连接SQL server,但不使用UNIX套接字,而是使用TCP:

psql postgres://postgres@localhost/smartbrain1
如果失败,可能意味着您的数据库已配置为不允许任何外部TCP连接

要允许本地主机访问postgres,应在pg_hba.conf中通过设置

host    all             all             127.0.0.1/32            trust
此外,您可能需要为您的postgres用户添加密码,并尝试在启用密码的情况下连接:

psql postgres://postgres:<password>@localhost/smartbrain1
psqlpostgres://postgres:@本地主机/smartbrain1
从命令行连接时,您可以在knex配置中尝试以下操作:

const db = knex({
  client: 'pg',
  connection: 'postgres://postgres:<password>@localhost/smartbrain1'
});
const db=knex({
客户:“pg”,
连接:'postgres://postgres:@本地主机/smartbrain1'
});

有关调试此问题的更多信息,请参见此处以及其他数十个常见的postgres数据库连接问题。

我可以添加有关请求的更多信息!刚刚更改了pga_hba.conf
const db = knex({
  client: 'pg',
  connection: 'postgres://postgres:<password>@localhost/smartbrain1'
});