从数据库中获取数据并显示在服务器上

时间:2019-04-26 09:36:55

标签: sql node.js postgresql sqlconnection

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

  

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

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

  

代码

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)

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

这种错误

  

无法连接到DBError:连接ECONNREFUSED

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