[英]How to i fetch value of client.query in Node JS with PG?
I am using node.js and make database connection with postgresql. 我正在使用node.js并与postgresql建立数据库连接。 My dbConfig.js look like :-
我的dbConfig.js看起来像: -
var pg = require('pg');
var client = new pg.Client({
host:'myhoost',
port:'5432',
user:'myuser',
password:'mypass',
database:'mydb',
ssl:true
});
client.connect();
module.exports.myconnection = client;
my api.js file look like :- 我的api.js文件看起来像: -
var dbConnect = require('./dbConfig.js');
var client = dbConnect.myconnection;
var ser = function(value) {
var query = "SELECT * FROM tbl_api WHERE apikey = '" + value + "'";
client.query(query, function(err, result) {
var res = true;
if (err) {
var res = false;
} else {
if (result.rowCount > 0) {
res = true;
} else {
res = false;
}
}
return res;
});
};
module.exports.checkAPI = ser;
my api.js look like:- 我的api.js看起来像: -
var express = require('express');
var app = express();
var apiCheck = require('./api.js');
//APIKey Generator check api
app.get('/apicheck/:apikey', function(request, response) {
var value = request.params.apikey;
var result = apiCheck.checkAPI(value);
response.send(result);
});
i want the res from client.query into the result variable. 我希望从client.query res到结果变量。 I found one same issue with mysqljs issue but still i am not able to solve this doubt.
我发现mysqljs问题同样存在问题,但我仍然无法解决这个问题。
We need the callback to finish to return a response, one of the way to solve this is using promises
as shown below: 我们需要回调来完成返回响应,其中一种解决方法是使用
promises
,如下所示:
var ser = function(value) {
var query = "SELECT * FROM tbl_api WHERE apikey = '" + value + "'";
return new Promise(function (resolve, reject) {
client.query(query, function(err, result) {
if (err) {
return reject(err);
} else {
if (result.rowCount > 0) {
return resolve(true);
}
}
return resolve(false);
});
});
};
module.exports.checkAPI = ser;
And in your api.js
changes to: 并在您的
api.js
更改为:
var express = require('express');
var app = express();
var apiCheck = require('./api.js');
//APIKey Generator check api
app.get('/apicheck/:apikey', function(request, response) {
var value = request.params.apikey;
apiCheck.checkAPI(value)
.then(function(result) { response.send(result); })
.catch(function(err) { response.send(err); });
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.