【问题标题】:Postgres database connection not working in node.jsPostgres 数据库连接在 node.js 中不起作用
【发布时间】:2021-07-24 21:59:33
【问题描述】:

我正在尝试使用 node-postgres 包连接我的数据库 postgres,但我的连接不工作。我设置了需要建立连接的每个参数,即使设置了所有参数,我也没有在日志中收到数据库已连接的消息。我错过了什么?

我的代码:

const { Pool } = require('pg');
const dotenv = require('dotenv');
dotenv.config();
const express = require('express');
const app = express(); 
const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'clinica-veterinaria',
    password: 'admin',
    port: 5432,
  })

pool.on('connect',() => {
    console.log('Conexão estabelecida com sucesso')
});

module.exports = {
    query: (text,params) => pool.query(text,params),
}
const flash = require('connect-flash');

const routes = require('./routes')
const path = require('path');


app.use(express.urlencoded({  extended:true }));

app.use(express.static(path.resolve(__dirname, 'public')));

app.use(flash());

app.set('views', path.resolve(__dirname, 'src', 'views'));
app.set('view engine', 'ejs');

app.use(routes);

app.listen(3000, () => {
    console.log('Acessar http://localhost:3000');
    console.log('Servidor executando na porta 3000');
});

【问题讨论】:

    标签: javascript database postgresql


    【解决方案1】:

    虽然您创建了池,但我没有看到您连接到 Postgre 服务器。更多信息请查看this document

    试试这个:

    const pool = new Pool({
        user: 'postgres',
        host: 'localhost',
        database: 'clinica-veterinaria',
        password: 'admin',
        port: 5432,
    });
    
    pool.connect((err, client, release) => {
        if (err) {
            return console.error('Error acquiring client', err.stack)
        }
        // Do what you have to do with the pool client now
    }
    

    【讨论】:

    • 乐于助人 ?
    猜你喜欢
    • 2021-06-26
    • 2021-07-10
    • 2013-10-31
    • 2016-01-31
    • 1970-01-01
    • 2011-09-09
    • 2013-05-09
    • 2014-12-27
    • 2014-05-20
    相关资源
    最近更新 更多