簡體   English   中英

Node.js和Heroku

[英]Node.js and Heroku

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} ); }
    });
  });
});

在哪里可以找到教程或對此的一些評論或解釋?

盡管我可以做一些猜測,但是很多這樣的代碼還是很神秘的。

目前,我主要關心的是:

  1. 如果我更改SQL查詢,將其替換為'SELECT count(*)FROM test_table',會發生什么情況? 然后如何呈現結果?
  2. 什么是“ done();” 做? 我可以修改或利用它嗎?
  3. 從不使用參數“ request”。 可以在某些時候使用它嗎?

在處理heroku之前,您應該首先查看node.js中有關Web應用程序的教程,它將回答您的最后一個問題。

您可以了解網絡框架express.js的工作方式。

然后查看node-postgre文檔。 您將在這里找到有關第二個問題的答案:

//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查詢后只記錄result輸出並查看得到的結果呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM