我正试图从我的postgres数据库中获取一些数据。但是当我尝试从postgres结果中获取json数据时,我总是收到错误。
这是我的Node JS代码:
pg.connect(connectionString, function(err, client, done) {
var pubKey;
var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);
query1.on('row', function(row) {
pubKey = row;
});
console.log(pubkey.pubkey);
}
umschlagInnen.sourceUserID是“2”
我的“用户”的姿势表如下所示:
users(userID int PRIMARY KEY, saltMaster varchar(255) not null, privKeyEnc varchar(2048) not null, pubKey VARCHAR(2048) not null)
错误:
ReferenceError: pubkey is not defined
你能找到我的错误吗?
答案 0 :(得分:0)
首先,pubKey变量的大小写出错:
pg.connect(connectionString, function(err, client, done) {
var pubKey;
var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);
query1.on('row', function(row) {
pubKey = row;
});
console.log(pubkey.pubkey); // broken version
console.log(pubKey.pubKey); // fixed version
}
但请记住,此console.log()将在查询回调函数执行之前执行,因此pubKey仍然无效。在回调函数中移动console.log(),它应包含您的数据。
试试这个:
pg.connect(connectionString, function(err, client, done) {
// var pubKey; <-- don't need this variable anymore
var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);
query1.on('row', function(row) {
console.log(row.pubKey);
// do something with the data here ...
});
}