2017-07-16 69 views
0

我在下面有ajax代碼,我想讀取我使用ajax發送的數據,我想讀取服務器端的數據。下面閱讀博客req在節點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); 
        } 
       }); 
      }); 

是我的服務器端節點的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-prser中間件,那麼一切都應該工作 –

回答

1

要發送使用jQuery阿賈克斯JSON有效載荷,你必須發送一個實際的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

謝謝,工作很好。 –