2016-11-09 41 views
0

Node.js和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. 參數「請求」從不使用。在某些情況下它可以用於 什麼?

回答

1

在處理heroku之前,您應該先看看node.js中有關web應用程序的教程,它將回答您最後的問題。

你可以看到如何工作express.js,一個web框架。

然後看看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 
    }); 
}); 

而且finanlly,你爲什麼不只需登錄result輸出改變SQL查詢後,看看你會得到什麼?

+0

非常感謝。我從這個答案中學到了很多東西。只有一個問題: 如何查看console.log(result.rows [0] .number)的結果; ?? 這必須是一個新問題。 – Michel

+0

@Michel我認爲最好的做法是使用別名。 'SELECT count(*)as count FROM test_table' then then count your result with'result.rows [0] .count' –

+0

是的,這完全是我在閱讀您的文章後的理解,但因爲我沒有得到結果當我嘗試時,我期待着。然後我去使用console.log,看不出來,我發現我一定是犯了一些錯誤或看錯了地方,並決定寫我的最後一條評論。 – Michel