0

Capstone プロジェクトに取り組んでおり、テレメトリ データをデータベースに保存する必要があります。データベースには PostgreSQL 9.5、サーバーにはノードを使用しています。

私の問題は、サーバーからクエリを送信しようとすると、クエリ エラー [エラー: 接続が終了しました] が表示されることです。使用するJSON.stringify(err)と、結果として空の括弧のみが表示されます{}。興味深いのは、pgAdmin クライアントを使用して同じクエリを実行すると、エラーが発生することなくレコードが正常に追加されることです。

クエリを送信するためにサーバーで使用しているコードは次のとおりです。

client.connect(function(err) {
    if(err){
        return console.error('could not connect to postgres', err);
    }

    //Checks if there is survey data to process
    if(surveyFlag){

        //Query to insert survey record
        //Returns survey record's auto-generated id to use it when creating or updating the             //telemetry record in the database 
        var query = 'INSERT INTO survey_response (perceived_risk, actual_risk) '+
                    'VALUES (' + telemetryRecord.survey.perceivedRisk +', ' +                   
                                 telemetryRecord.survey.actualRisk +') ' +
                    'RETURNING survey_id';

        client.query(query, function(err, result) {

        console.log("Query: " + query);

                if(err) {
                    console.log(err);
                    return console.error('error running survey query', err);
                }

                surveyID = result.rows[0].survey_id;    

                //Testing
                console.log ("Survey response added with ID: " + surveyID);


        });

            //Close the connection  
        client.end();
});
4

1 に答える 1

1

コードclient.end()はコードと同じレベルに置かれますclient.query()client.query()は非同期であるためclient.end()、クエリを開始した直後に が呼び出されます。クエリが戻ってくるまでに、クライアントはすでに終了しており、これが問題の原因となっています。

client.end()のコールバック関数内にコードを配置してみてくださいclient.query()

client.query(query, function(err, result) {
  console.log("Query: " + query);

  if(err) {
    console.log(err);
    return console.error('error running survey query', err);
  }

  surveyID = result.rows[0].survey_id;    

  //Testing
  console.log ("Survey response added with ID: " + surveyID);

  //Close the connection  
  client.end();

});
于 2015-10-13T20:57:58.233 に答える