【问题标题】:Fetching data from database and displaying on server从数据库中获取数据并显示在服务器上
【发布时间】:2019-04-26 19:00:52
【问题描述】:

我正在尝试使用 PostgreSQL 编写节点 js 代码以从数据库中获取数据并显示在浏览器上。当程序运行时,控制台显示以下消息:

服务器正在运行.. 在端口 4000

但是,当我们尝试在网络浏览器上运行该程序时,它会显示以下错误。

代码

const pg        = require('pg');
const express   = require('express');
const app       = express();

const config = {
    user: 'postgres',
    database: 'student',
    password: 'student',
    port: 5432
};

// pool takes the object above -config- as parameter

const pool = new pg.Pool(config);

app.get('/', (req, res, next) => {
   pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
       }
       client.query('SELECT * FROM country()', function (err, result) {
            done();
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
       })
   })
});

app.listen(4000, function () {
    console.log('Server is running.. on Port 4000');
});

错误

Can not connect to the DBError: connect ECONNREFUSED 127.0.0.1:5432
F:\DatabaseProject6\server.js:52
       client.query('SELECT * FROM country()', function (err, result) {
              ^

TypeError: Cannot read property 'query' of undefined
    at PendingItem.callback (F:\DatabaseProject6\server.js:52:15)
    at client.connect (F:\DatabaseProject6\node_modules\pg-pool\index.js:248:23)
    at Connection.connectingErrorHandler (F:\DatabaseProject6\node_modules\pg\lib\client.js:163:14)
    at Connection.emit (events.js:189:13)
    at Socket.reportStreamError (F:\DatabaseProject6\node_modules\pg\lib\connection.js:71:10)
    at Socket.emit (events.js:189:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

可能是什么问题?

【问题讨论】:

  • 检查您的数据库凭据/用户名/密码。

标签: sql node.js postgresql sqlconnection


【解决方案1】:

这种错误

无法连接到 DBError: connect ECONNREFUSED

通常是因为您的 PostgreSQL 服务器未运行、您的凭据错误或您的数据库不存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多