2016-05-14 11 views
1

私はhttp.createServerレスポンスに問題があります。nodejs、他の関数からの応答を呼び出す/渡す方法

私は、ユーザーPOSTから本体を解析し、それを自分の関数に渡す関数onRequestを持っています。私は関数の終了クエリの後にクライアントに応答を送信したいと思いますが、匿名関数内では定義されていないため、関数に応答を渡すことができません。

function onRequest(request, response){ 
    console.log("Request received."); 
    if (request.method == 'POST'){ 
     var body =' '; 
     request.on('data', function(data){ 
      body += data; 
     }); 

     request.on('end', function(){ 
      var as = JSON.parse(body); 
      spatial_index_query(as['x'], as['y'], response); 
     }); 
    } 
} 
http.createServer(onRequest).listen(8013, '0.0.0.0'); 

My機能

function spatial_index_query(x, y, res) { 
    db.get("Select id from spatial_index where minX < ? AND minY < ? AND maxX > ? AND maxY > ?",[x, y, x, y], 
     function(err, rows, res){ 
      response.writeHead(200, {"Content-Type":"text/plain"}); 
      response.write('it works'); 
      response.end(); 
     }; 

それは動作しません。

今、私はこの

function test(response){ 
    console.log(response); 
}; 

のように正常な機能への応答を渡すしようとする場合、それは動作しますが、私は内部の無名関数を持つ関数への応答を渡ししようとしていた場合、それは応答が未定義であることが判明。

このような状況でレスポンスを使用する適切な方法は何ですか?

私はこの

function spatial_index_query(x, y) { 
    db.get("Select id from spatial_index where minX < ? AND minY < ? AND maxX > ? AND maxY > ?",[x, y, x, y], 
     function(err, rows){ 
      return 'it works' 
      // how to call response now? 
     }; 

のようなものに私の機能を変えることができるが、私は今の応答を呼び出す方法は考えています。

また、onRequest関数内でresult()関数を作成しようとしましたが、queryとpassの後に関数から呼び出すことができましたが、result()はonRequest関数の外では表示されません。

EDIT
私は機能の代わりにresを使用しました。固定機能:

function spatial_index_query(x, y, response) { 
    db.get("Select id from spatial_index where minX < ? AND minY < ? AND maxX > ? AND maxY > ?",[x, y, x, y], 
     function(err, rows){ 
      response.writeHead(200, {"Content-Type":"text/plain"}); 
      response.write('it works'); 
      response.end(); 
     }; 
+4

あなたが名前を 'response'または' res.writeHeadを書くのいずれかを行う必要があります引数は 'res'ない' response'( '関数spatial_index_query(X、Y、RES)')と命名されているので、 '、... –

+0

質問を編集するのではなく、回答セクションに回答を入れる必要があります(私は投票できます)... – Soren

答えて

0

私の機能には、誤植がありました。固定機能:

function spatial_index_query(x, y, response) { 
db.get("Select id from spatial_index where minX < ? AND minY < ? AND maxX > ? AND maxY > ?",[x, y, x, y], 
    function(err, rows){ 
     response.writeHead(200, {"Content-Type":"text/plain"}); 
     response.write('it works'); 
     response.end(); 
    }; 
関連する問題