【发布时间】:2022-01-24 00:43:35
【问题描述】:
您好,我正在尝试从 api/data.js 提供的 server/index.js api 端点 data.getData() 获取数据,后者又从 db/index.js 获取其配置和连接对象。问题是 async/await 没有返回任何内容,并且在开发控制台网络中显示待处理。我也没有收到任何错误。代码如下。将 node-pg 与 pool.query 一起使用。
//server/index.js
const express = require("express");
const data = require("./api/data")
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json())
app.get('/', async (req, res) => {
// res.status(200).send('Hello World!');
await data.getData()
.then(response => {
res.status(200).send(console.log(response));
})
.catch(error => {
res.status(500).send(error);
})
console.log("server running")
})
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
//api/data.js
const db = require('../db/index.js');
const getData = async () => {
const query = {
// text: 'SELECT COUNT(*) as count FROM "public"."Subregions-USA";',
text: 'SELECT Now()',
// values: ['B007RKDGVQ'],
// rowMode: 'array',
};
const dbResults = await db.query(query)
.then((data) => JSON.stringify(data))
.catch(error => {
console.log(error)
})
console.log("database response test")
return dbResults
}
// getData()
module.exports = {getData}
我正在尝试连接到数字海洋中的 postgresql,并且所有连接和配置都是正确的。我使用了类似的相同设置,但使用了 electron.js 并且它可以工作。我能够轻松检索数据。
任何帮助表示赞赏。
【问题讨论】:
-
res.status(200).send(response); -
@hoangdv 我试过它不起作用,我尝试了几件事,无法发送响应并控制台它。
-
尽量让你的代码更干净。如果您使用
.then/catch,请不要使用async/await。如果您使用async/await,请不要使用then/catch。我猜console.log(error)线被调用了。 -
那么你的代码记录了什么?它挂在哪里?
标签: node.js postgresql async-await node-pg-pool