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

Sending data from javascript/html page to Express NodeJS server

我正在开发一个 cordova 应用程序,使用 html5 和 javascript。

架构如下:phone 应用程序向服务器请求某些内容,服务器请求 firebird 数据库。数据库回答服务器,服务器将请求的数据提供给 phone 应用程序(在 html5 / javascript 中)。

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

因此考虑以下 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})

如何在我的 Node 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);
});

我发表评论是为了让你知道我已经尝试过什么(还有更多)... 每次,请求的类型要么被定义要么是一个对象,但由于它是循环的我无法解析它所以我不确定它是从 phone 应用程序发送的数据。

那么你能否给我一些建议,解释一下如何将数据从 phone 发送到服务器? (我想我可以尝试在服务器解析的 url 中显示数据,但我宁愿不必这样做以保护数据...)。

如有任何帮助,我们将不胜感激!非常感谢你 !

(PS : 我已经到处寻找一些答案,但还没有奏效)

req 是一个充满了每个请求附带的东西的对象。您需要获取请求的正文。这可能对您有帮助:How to retrieve POST query parameters?

但是因为没有太多的客户端 JavaScript 我想问一下:你有没有指定你想要 POST 这个?

试试看这里: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
});