我正在使用Nodejs,express和postgresql创建rest api。这是我第一次进行任何此类操作,因此我对此表示歉意。我刚刚进行了测试,似乎打算从本地数据库中检索信息,但是当我尝试使用res.json()发送数据时,什么都没有显示。这是我到目前为止的代码。
var express = require('express');
var client = new pg.Client({user: 'xxx', password: 'xxx', database: 'xxx', host: 'xxx'});
var app = express();
app.get('/test1', function(req,res){
var name;
client.connect(function(err){
if(err){
return console.error('could not connect to postgres', err);
}
client.query("select classname from class", function(err, result){
if(err){
return console.error('error running query', err);
}
name = result.rows[0].classname;
console.log(name);
client.end();
});
});
res.send(name);
});
我使用了控制台日志,并打印出了我需要的日志,但是由于某些奇怪的原因,它无法发送。谢谢您的帮助!另外,如果您发现其他任何错误,请不要害怕地说出来。谢谢!
这是一个异步函数,因此将如下所示:
var express = require('express');
var client = new pg.Client({
user: 'xxx',
password: 'xxx',
database: 'xxx',
host: 'xxx'
});
var app = express();
app.get('/test1', function(req, res) {
var name;
client.connect(function(err) {
if (err) {
return console.error('could not connect to postgres', err);
}
client.query("select classname from class", function(err, result) {
if (err) {
return console.error('error running query', err);
}
name = result.rows[0].classname;
console.log(name);
client.end();
res.send(name);
});
});
});
您的代码中正在发生的事情是您在查询执行完成之前先进行发送。您可以在控制台上看到它,因为查询后您的log语句可以正确执行。
另外,您还应该注意自己的错误-因此,不要返回带有一些错误消息的另一个res.send(或res.json),而不是返回它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句