2017-07-16 9 views
0

のポストreqがあります。私は以下のajaxコードを持っています。私はajaxを使って送信しているデータを読み込みたいのですが、サーバー側のデータを読み込みたいです。以下ノードjs

 $.ajax({ 
        type: 'POST', 
        data: {hurl: "test data"}, 
        contentType: 'application/json', 
        url: 'http://localhost:5000/hmap', 
        success: function(data) { 
//       console.log('success'); 
//       console.log(JSON.stringify(data)); 

         console.log(data); 
        } 
       }); 
      }); 

のjQueryのAjaxを使用してJSONペイロードを送信するために私のサーバー側ノードjsのコード

var hmapdata = []; 
app.post('/hmap', function(req, res) { 
    console.log(req.body); 
    MongoClient.connect(url, function(err, db) { 
     if (err) 
      throw err; 
     db.collection("heatmap").find().toArray(function(err, result) { 
      if (err) 
       throw err; 
      hmapdata = result; 

      db.close(); 
     }); 
    }); 
    setTimeout(function() { 
     res.send(hmapdata); 
    }, 1000); 
}); 
+0

あなたのreq.bodyを使用すると、Ajaxリクエストから送信されたデータが含まれていません。その –

+0

を使用して、開発ツールの[ネットワーク]タブを使用して、POST呼び出しに関する詳細情報を収集します。 –

+0

しかし、何が問題なのですか? body-parserミドルウェアを使用している場合は、すべてが動作するはずです –

答えて

1

で、あなたは実際のJSON文字列ではなく、JavaScriptのオブジェクトを送信する必要があります。

だから、実行する必要があります:

data: JSON.stringify({ hurl: "test data" })

enter image description here

これは、あなたが送信しているものである:あなたのサーバーで今

enter image description here

、あなたが」 body-parserミドルウェアを使用すると、投稿されたJSONは0123で利用可能になります上

app.use(bodyParser.json()); 

app.post('/hmap', function(req, res) { 
    console.log(req.body); // req.body.hurl == "test data" 
}); 

詳細:jQuery posting valid json in request body

+0

ありがとうございました。 –