我正在尝试从pg数据库中获取一些数据到我的api端点,我可以将结果打印到控制台,但是无法使用res.send将其显示在浏览器中。我猜测问题出在全球范围和本地范围,但是我无法弄清楚。我正在使用ES6,但使用Babel进行转译。这是一个片段。
app.get('/', (request, response) => {
const { Pool, Client } = require('pg');
const config = {
user: '',
host: '',
database: '',
password: '',
port: ,
}
const pool = new Pool(config);
const client = new Client(config);
let whole = [];
client.connect();
const text = "SELECT * FROM entries where id='1'";
client.query(text)
.then(res => {
console.log(res.rows[0]);
whole.push(res.rows[0]);
})
.catch(e => console.error(e.stack));
response.send(whole);
client.end;
});
这将记录到控制台
{ id: 1, title: 'First title', body: 'beautiful body' }
但是浏览器仅显示[] 这是babel将其转换为我在node中运行的脚本的原因。
var whole = [];
client.connect();
var text = "SELECT * FROM entries where id='1'";
client.query(text).then(function (res) {
console.log(res.rows[0]);
whole.push(res.rows[0]);
}).catch(function (e) {
return console.error(e.stack);
});
response.send(whole);
client.end;
答案 0 :(得分:0)
response.send在异步promise .then解析器之外调用,因此在将行数据推入数组之前执行。将response.send移到Promise解析器中应该可以解决它。
client.query(text).then(res => {
whole.push(res.rows[0]);
client.end();
response.send(whole);
}).catch((e) => {
console.error(e.stack);
});
或者,您可以根据babel版本和预设/插件来使用async / await。
const { Client } = require("pg");
const config = {...};
const queryText = "SELECT * FROM entries where id='1'";
app.get("/", async (request, response) => {
const client = new Client(config);
await client.connect();
try {
const queryResponse = await client.query(queryText);
// Send response without pushing to array
response.send(queryResponse.rows[0]);
client.end();
} catch (e) {
console.error(e.stack);
}
});