2012-02-15 3 views
2

노드에서 데이터베이스를 쿼리 할 때 비동기 콜백에 HTTP 응답 객체를 전달하는 방법은 무엇입니까? (예를 들면, DB 물건이 의사 코드)Node.js의 콜백에 HTTP 응답을 전달하는 방법은 무엇입니까?

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

콜백 함수 선언에 응답을 추가하면 콜백 함수에서만 범위가있는 새로운 null 응답 객체가 생성됩니다.

대신 응답 매개 변수를 제거하면됩니다.

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

이 콜백 함수 내에서 변수 응답은 이제 createServer 콜백의 원래 응답 변수를 참조합니다. 이 함수는 createServer 콜백 내부에 있으므로 응답 객체에 액세스 할 수 있습니다.

-3

사용 repsonse.send(index)

기본적으로, 당신은 내부에 어떤 기능이 볼 만 응답 객체를 인쇄 할 수 있습니다.

console.log(response)

관련 문제