2017-07-16 68 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

谢谢,工作很好。 –