ndr*_*zza 7 json request node.js
我正在向node.js发送带有以下请求的凭证JSON对象:
credentials = new Object();
credentials.username = username;
credentials.password = password;
$.ajax({
type: 'POST',
url: 'door.validate',
data: credentials,
dataType: 'json',
complete: function(validationResponse) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,我想将提交的凭据加载到JSON对象中以进一步使用它.
但是,我不知道如何从req对象中获取JSON ...
http.createServer(
function (req, res) {
// How do i acess the JSON
// credentials object here?
}
).listen(80);
Run Code Online (Sandbox Code Playgroud)
(我在我的函数(req,res)中有一个调度程序,将req进一步传递给控制器,所以我不想使用.on('data',...)函数)
dav*_*tto 16
在服务器端,您将收到jQuery数据作为请求参数,而不是JSON.如果您以JSON格式发送数据,您将收到JSON并需要解析它.就像是:
$.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) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,您将:
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);
Run Code Online (Sandbox Code Playgroud)
请注意,这将适用于GET.要获取POST数据,请看一下:如何在Node.js中提取POST数据?
要将对象序列化为JSON并在jsonData中设置值,您可以使用JSON.stringify(credentials)(在最新的浏览器中)或JSON-js.这里的示例:在jQuery中序列化为JSON