Node.js 和 Heroku 入门;我正在尝试理解以下代码,以便构建我自己的东西:
app.get('/db', function (request, response) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
client.query('SELECT * FROM test_table', function(err, result) {
done();
if (err)
{ console.error(err); response.send("Error " + err); }
else
{ response.render('pages/db', {results: result.rows} ); }
});
});
});
在哪里可以找到教程或一些评论或解释?
尽管我可以进行一些猜测,但这段代码的大部分内容都非常神秘。
目前我主要关心的是:
- 如果我更改 SQL 查询,将其替换为“SELECT”,会发生什么情况 count(*) FROM test_table'?然后如何呈现结果?
- “done();”是什么意思做?我可以修改或使用它吗 的?
- 从未使用过参数“request”。可以用于 在某个时刻做某事?
最佳答案
在处理heroku之前,您应该首先查看有关node.js中的Web应用程序的教程,这将回答您的最后一个问题。
您可以查看如何工作 express.js ,一个网络框架。
然后看node-postgre文档。您将找到关于第二个问题的答案here :
//this initializes a connection pool
//it will keep idle connections open for a 30 seconds
//and set a limit of maximum 10 idle clients
var pool = new pg.Pool(config);
// to run a query we can acquire a client from the pool,
// run a query on the client, and then return the client to the pool
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query('SELECT $1::int AS number', ['1'], function(err, result) {
//call `done()` to release the client back to the pool
done();
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].number);
//output: 1
});
});
最后,为什么不在更改 SQL 查询后记录 结果
输出并查看得到的结果?
关于javascript - Node.js 和 Heroku,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505646/