2012-02-15 51 views
2

從Node查詢數據庫時,如何將HTTP響應對象傳遞給aysynchronous回調?例如(分貝東西是僞代碼):如何將HTTP響應傳遞給Node.js中的回調?

var http = require('http'); 
http.createServer(function (request, response) { 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    // read from database: 
    var dbClient = createClient(myCredentials); 
    var myQuery = 'my query goes here'; 
    dbClient.query(myQuery, callback); 

    function callback(error, results, response) // Pass 'response' to the callback? 
    { 
    if (error === null) { 
     for (var index in results) response.write(index); // Error 
     response.end('End of data'); 
    } 
    else { 
     response.end('Error querying database.') 
    } 
    } 
}).listen(1337, "127.0.0.1"); 

當傳遞response到回調,節點給出的結果繼續對象沒有方法write錯誤。

這裏最好的策略是什麼?

回答

3

通過在回調函數聲明中放置響應,您正在創建一個僅在回調函數中具有作用域的新的空響應對象。

相反,您只需刪除響應參數即可。

function callback(error, results) // response is outside of function 

而在此回調函數中,變量響應現在將引用createServer回調的原始響應變量。由於此函數位於createServer回調的內部,因此它將有權訪問響應對象。

-3

使用repsonse.send(index)

基本上,你可以只打印response對象,看看有什麼功能都在裏面。

console.log(response)

相關問題