将数据从数据库(db.js)返回到节点(app.js)时出现问题

时间:2019-12-01 23:23:33

标签: node.js postgresql

我试图通过发布请求从node.js中的postgres数据库请求数据。最终,这些数据将被发送到一个响应前端。 我从数据库中获取了正确的数据,但似乎无法将这些数据返回给app.js(我有点像node.js noob)。我有两个文件app.js和db.js

这是app.js

const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors')
const db = require('./db')
const bodyParser = require('body-parser')
const middlewares = require('./middlewares');


const app = express();
app.use(cors());
app.use(morgan('dev'));
app.use(helmet());
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(bodyParser.urlencoded({ extended: false }))
// Parse JSON bodies (as sent by API clients)
app.use(express.json());

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  next();
});

app.get('/api', (req, res) => {
  res.send({ express: 'Server online' });

});

app.post('/layer', (req, res, next) => {
  var layer = req.body.menu;
  var geometry = db.layer(layer);
  console.log(geometry);
  res.set('Content-Type', 'application/json')
  //const body = res.body()
});


app.use(middlewares.notFound);
app.use(middlewares.errorHandler);

module.exports = app;

这是db,js

const { Pool, Client } = require('pg')

const connection = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'dbtemp',
    password: 'password',
    port: 5432,
    max: 20,
    connectionTimeoutMillis: 2000,
})
connection.connect(function(err) {
    if (err) throw err;
});

connection.on('connect', () => {
console.log("connected to database on port: " );
});

module.exports = { 
    layer: function(layer) { 
        connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
            if (err) {
                return console.error('Error executing query', err.stack)
            }
            var geometry = result.rows[0].st_asgeojson;
            console.log(geometry);
            return result;
        })
    }
}

我从db.js获取正确的数据记录到控制台 输出:

Listening: http://localhost:5000
connected to database on port:
Promise { undefined }
connected to database on port:
{"type":"MultiLineString","coordinates":[[[1797202.15,5753380.18,0],[1797200.87,5753384.48,0],[1797198.16,5753393.62,0],[1797197.78,5753404.37,0],[1797200.38,5753428.48,0],[1797217.82,5753566.48,0],[1797225.98,5753623.6,0],[1797227.09,5753645.86,0],[1797225.98,5753665.52,0],[1797223.38,5753684.07,0],[1797213.95,5753717.71,0]]]}

如何将查询结果发送到app.js并发送到网页(反应前端)。我猜数据准备就绪时需要回调吗?

1 个答案:

答案 0 :(得分:0)

您可能要考虑使用Promise或callbacks

  1. 承诺方式

db.js

...
module.exports = { 
    layer: function(layer) { 
        return new Promise((resolve, reject) => {
            connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
                if (err) {
                    console.error('Error executing query', err.stack)
                    return reject(err);
                }
                var geometry = result.rows[0].st_asgeojson;
                console.log(geometry);
                return resolve(result);
            })
        })
    }
}

app.js

...
app.post('/layer', async (req, res, next) => {
    var layer = req.body.menu;
    var geometry = await db.layer(layer);
    console.log(geometry);
    res.set('Content-Type', 'application/json')
    //const body = res.body()
});
  1. 回调方法

db.js

module.exports = { 
    layer: function(layer, cb) { 
        connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
            if (err) {
                console.error('Error executing query', err.stack)
                return cb(err)
            }
            var geometry = result.rows[0].st_asgeojson;
            console.log(geometry);
            return cb(null, geometry);
        })
    }
}

app.js

...
app.post('/layer', (req, res, next) => {
    var layer = req.body.menu;
    db.layer(layer, (err, geometry) => {
        if (err) throw err;
            console.log(geometry);
    res.set('Content-Type', 'application/json')
    //const body = res.body()
    });
});