我需要在本地与PostgreSQL数据库进行通信,但是我面临的问题是代码跳过了回调函数。
queries.js
const pg = require('pg')
const pool = new pg.Pool({
user: 'postgress',
database: 'cube',
password: 'password',
port: 50764
})
var query = (queryString) => {
pool.connect(function (err, client, done) {
if (err) {
console.log('Can not connect to the DB' + err)
}
res = client.query(queryString, function (err, result) {
done()
if (err) {
console.log(err)
}
})
})
pool.end()
}
module.exports = {
query
}
会有多个脚本处理数据库的不同表,因此我将连接放在另一个文件(queries.js)上并导出函数查询,以便这些脚本可以通信而无需重复代码。
pool.connect内部的任何代码都不会被调用,并且调试会直接转到pool.end()所在的行。
我已经完成的事情:
我使用了Tania Rascia的本指南,将Node.js和PostgreSQL https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8设置为RESTful API,并将其更改为我的需要。
我尝试使用提供的文档https://node-postgres.com/features/pooling来更正代码,但是问题仍然存在,所以我认为它可以处理我正在使用的配置数据,用户名和密码是我所使用的用来登录pgAdmin,数据库名称是我拥有的数据库列表上的same,当我在browser上打开端口时,端口号由PostgreSql提供。
稍后我将在heroku.com上部署它,我不知道它是否会影响您的答案。
谢谢。