从javascript / html页面发送数据到Express NodeJS服务器

我正在使用html5和javascript编写一个cordova应用程序。

该体系结构如下:电话应用程序向服务器请求一些东西,要求一个firebird数据库。 数据库应答服务器,向电话应用程序提供所要求的数据(在html5 / javascript中)。

我已经能够使用JSON将数据从服务器发送到手机,我认为从手机应用程序发送一些数据到服务器也是一样的。 但是,我不知道如何从手机发送数据到这样的服务器。 我试图尽可能简化问题。

所以考虑下面的JavaScript代码:

var send = { "name":"John", "age":30, "car":null }; var sendString = JSON.stringify(send); alert(sendString); xhttp.send(sendString); 

(警报发送给我:{“name”:“John”,“age”:30,“car”:null})

我如何检索我的节点JS服务器? 目前,我的代码是以下一个:

 app.post('/createEmp', function(req, res){ //res.send(req.body.name); //console.log('test :' + req.app.post('name')); //console.log(req); console.log('createEmp'); if(typeof(req) == 'undefined') {console.log('Y a rien'); } else { console.log('La req n est pas vide, son type est : ' + typeof req); } console.log(typeof req.query.name); }); 

我让评论,让你知道我已经试过(还有更多)…每一次,req的types要么定义,要么是一个对象,但由于它是循环的,我不能parsing它,米不知道这是从电话应用程序发送的数据。

那么请你给我一个build议,关于如何将数据从手机发送到服务器的说明? (我想我可以尝试显示的数据将由服务器parsing的URL,但我宁愿不必这样做,以保护数据…)。

任何帮助,将不胜感激 ! 非常感谢你 !

(PS:我已经在寻找一些答案,但没有任何工作)

req是一个充满了每一个请求的东西的对象。 你需要得到你的请求的身体。 这可能会帮助你: 如何检索POST查询参数?

但是因为没有太多的客户端JavaScript我不问: 你有没有指定你想发布这个?

试试像这样: https : //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send …当你使用xhr.setRequestHeader(“Content-Type”,“application / json “)你可能不需要把它串起来。

首先在客户端做这个..

 var send = { "name":"John", "age":30, "car":null }; var sendString = JSON.stringify(send); alert(sendString); xhttp.send(send); 

然后在服务器端,你需要添加一个中间件来填充请求对象中的body参数。

 var express=require("express"); var bodyParser=require("body-parser"); var app=express(); // Process application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: true})) // Process application/json app.use(bodyParser.json()); app.post('/createEmp', function(req, res){ //now req.body will be populated with the object you sent console.log(req.body.name); //prints john });