node.jsparsing请求的JSON

我发送凭证JSON对象与下面的请求到node.js:

credentials = new Object(); credentials.username = username; credentials.password = password; $.ajax({ type: 'POST', url: 'door.validate', data: credentials, dataType: 'json', complete: function(validationResponse) { ... } }); 

在服务器端,我想加载提交的凭据到一个JSON对象进一步使用它..

但是,我不知道如何获得需求对象的JSON …

 http.createServer( function (req, res) { // How do i acess the JSON // credentials object here? } ).listen(80); 

(我有一个调度员在我的函数(REQ,RES)进一步传递给控制器​​,所以我不想使用.on('data',…)函数)

在服务器端,您将收到jQuery数据作为请求参数,而不是JSON。 如果您以JSON格式发送数据,您将收到JSON并需要parsing它。 就像是:

 $.ajax({ type: 'GET', url: 'door.validate', data: { jsonData: "{ \"foo\": \"bar\", \"foo2\": 3 }" // or jsonData: JSON.stringify(credentials) (newest browsers only) }, dataType: 'json', complete: function(validationResponse) { ... } }); 

在服务器端,你会做:

 var url = require( "url" ); var queryString = require( "querystring" ); http.createServer( function (req, res) { // parses the request url var theUrl = url.parse( req.url ); // gets the query part of the URL and parses it creating an object var queryObj = queryString.parse( theUrl.query ); // queryObj will contain the data of the query as an object // and jsonData will be a property of it // so, using JSON.parse will parse the jsonData to create an object var obj = JSON.parse( queryObj.jsonData ); // as the object is created, the live below will print "bar" console.log( obj.foo ); } ).listen(80); 

请注意,这将使用GET。 要获取POST数据,请看这里: 如何在Node.js中提取POST数据?

要将对象序列化为JSON并在jsonData中设置值,可以使用JSON.stringify(credentials) (在最新的浏览器中)或JSON-js 。 这里的例子: 在jQuery中序列化为JSON

Console.log请求

 http.createServer( function (req, res) { console.log(req); // will output the contents of the req } ).listen(80); 

发布的数据将在那里,如果它被成功发送。