首页 > 解决方案 > 从节点 js 连接到 postgresql db

问题描述

我很想从我的 nodejs 脚本连接到我的数据库连接,但似乎有一个我无法弄清楚的可疑问题。

目前,这是我的代码:

const { Pool } = require('pg');
const pool = new Pool({
    user: 'user',
    host: '192.168.1.xxx',
    database: 'database',
    password: 'password',
    port: 5432,
});
pool.on('error', (err, client) => {
    console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
    .then((client) => {
        client.query(query)
            .then(res => {
                for (let row of res.rows) {
                    console.log(row);
                }
            })
            .catch(err => {
                console.error(err);
            });
    })
    .catch(err => {
        console.error(err);
    });

问题似乎出在 pool.connect() 中,但我无法理解我缺少什么,因为我在日志中没有错误。我已经使用npm install --prefix pg在我的项目目录中安装了 pg 模块,并且我知道模块已正确加载。我编辑了 postgresql.conf:

# - Connection Settings -
listen_addresses = '*'

和 pg_hba.conf

host    database       user          192.168.1.0/24          md5

使数据库可以通过 lan 访问,并且似乎可以正常工作,因为我能够成功地连接到 DBeaver 等应用程序......但我不能使用 NodeJS。

有可能我要激活某种配置吗?

标签: node.jspostgresql

解决方案


推荐阅读