【问题标题】:How to connect Node.js app to postgresql on Ubuntu server?如何将 Node.js 应用程序连接到 Ubuntu 服务器上的 postgresql?
【发布时间】:2023-08-15 10:02:01
【问题描述】:

我启动了服务器。在那里安装了 nodejs、nginx、postgres、ufw 等等。该网站正在运行。连接到 postgres 的问题。我启动了服务器。在那里安装了 nodejs、nginx、postgres、ufw 等等。该网站正在运行。问题是连接到 postgres。它在连接中,而不是在查询中,因为我尝试了很多 sql 查询,但它只是忽略了 client.query()。 Postgres 默认设置和配置。我没有改变任何东西。

在配置文件中#listening_address 是注释。

由 node-postgres 使用。

const { Client } = require('pg');
const client = new Client({
  user: 'admin', //tried postgres
  host: '127.0.0.1', //tried *, site ip
  database: 'passport', //tried other DB
  password: 'secretpass', //installed through $passwd postgres, #ALTER USER admin with password ''
  port: 5432,
});
client.connect();

app.post('/confirm', urlencodedParser, function (req, res){
  let uid = uuidv4();
  let query= {
    text : 'INSERT INTO users(uid, name, surname, birthday, gender, email, password, region, language) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9);',
    values : [uid, user.name, user.surname, user.birthday, user.gender, user.email, user.password, user.region, user.region]
  }

  client.query(query, (err, result) => { // I have tried many sql queries, but it just ignores client.query()

    // console.log('some text');  doesn't display
    if (err) {
      console.log(err.stack)
    } else {
        res.render('addsite', {user: user});
      }
  });
});

/etc/postgresql/9.5/main/postgresql.conf

# i didn't change anything
data_directory = '/var/lib/postgresql/9.5/main'
hba_file = '/etc/postgresql/9.5/main/pg_hba.conf'
ident_file = '/etc/postgresql/9.5/main/pg_ident.conf'

external_pid_file = '/var/run/postgresql/9.5-main.pid'
port = 5432 
max_connections = 100
unix_socket_directories = '/var/run/postgresql' 
ssl = true
ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem'
ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'
shared_buffers = 128MB
dynamic_shared_memory_type = posix
log_line_prefix = '%t [%p-%l] %q%u@%d '
log_timezone = 'Etc/UTC'
stats_temp_directory = '/var/run/postgresql/9.5-main.pg_stat_tmp'

datestyle = 'iso, mdy'
timezone = 'Etc/UTC'
lc_messages = 'en_US.UTF-8' 
lc_monetary = 'en_US.UTF-8' 
lc_numeric = 'en_US.UTF-8'
lc_time = 'en_US.UTF-8'

default_text_search_config = 'pg_catalog.english'

/etc/postgresql/9.5/main/pg_hba.conf

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

请帮帮我!!!

【问题讨论】:

    标签: node.js postgresql pg node-postgres


    【解决方案1】:

    大家都需要使用pg的connect方法连接数据库。

    添加配置后:

    client.connect()
    

    只有这样你才能开始查询你的数据库。

    有关更多信息,请查看此连接链接:https://node-postgres.com/features/connecting

    【讨论】:

      【解决方案2】:

      因为您的 pg_hba.conf 看起来好像没有被触及。 看看那几行:

      # Database administrative login by Unix domain socket
      local   all             postgres                                peer    
      # "local" is for Unix domain socket connections only
      local   all             all                                     peer
      

      这告诉你数据库只能通过对等身份验证模式访问。 为此,您应该使用 postgres 凭据访问数据库。

      $sudo su postgres
      

      之后,系统会提示您输入 linux 中超级用户的密码。密码成功后,您应该会看到您的 bash 提示标签更改为:

      postgres@<yourlinuxinstance>
      

      现在您可以使用对等身份验证模式访问 postgres 数据库。

      $psql -U postgres
      #should login in postgres with success
      postgres=#
      

      在 psql 命令行中,您现在应该创建访问数据库的用户和密码。

      CREATE USER foo WITH ENCRYPTED PASSWORD '-+mysecurepasswordforthisuser+-';
      CREATE DATABASE passport;
      GRANT ALL PRIVILEGES ON passport TO foo;
      \q #exit psql shell
      $exit #exit from su session with postgres username
      

      之后你必须访问pg_hba.conf文件并更改访问方法,将peer更改为md5

      # "local" is for Unix domain socket connections only
      local   all             all                                     md5
      

      重启数据库

      $sudo service postgresql restart
      

      之后,您可以在连接字符串中配置当前添加的用户密码和数据库。

      现在您应该可以成功地从您的 nodejs 代码访问您的数据库了。

      如果您需要一些澄清,您可以access this guide

      【讨论】:

        最近更新 更多