从Object.js服务器接收来自Object格式的Ajax调用的数据

时间:2013-07-18 12:49:02

标签: ajax json node.js

我正在使用Ajax调用将数据从客户端发布到节点服务器并尝试在服务器端接收数据,操作它(执行一些数据库查询)然后返回响应。

客户端代码:

$.ajax({
    type: "post",
    url: "http://localhost:8888/ajaxRequest", 
    dataType: "json",
    data:  {name: "Manish", address: {city: "BBSR", country: "IN"}}
}).done(function ( data ) {
    console.log("ajax callback response:" + data);
});

服务器端:

var port = 8888;
var server = http.createServer();
server.on('request', request);
server.listen(port);

function request(request, response) {
    var store = '';
    response.writeHead(200, {"Content-Type": "text/json"});
    request.on('data', function(data) {
        store += data;
    });
    request.on('end', function() {
        console.log(store);
        response.end(store);
    });
}

问题:当我在请求结束函数中安慰“store”变量时,我得到的结果如下:

name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN

我只想在服务器端获取与Ajax“data”参数中发送的相同的数据。我也试过,queryString.parse,JSON.parse()但没有帮助。我只想要输出:

{name: "Manish", address: {city: "BBSR", country: "IN"}}

2 个答案:

答案 0 :(得分:2)

你需要告诉jQuery这是一个JSON请求:

$.ajax({
    type: "post",
    url: "http://localhost:8888/ajaxRequest", 
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    data:  JSON.stringify({name: "Manish", address: {city: "BBSR", country: "IN"}})
}).done(function ( data ) {
    console.log("ajax callback response:" + data);
});

这样,您的请求正文将使用字符串化的JSON到达服务器,因此您将能够执行以下操作:

request.on('end', function() {
    store = JSON.parse(store);
    console.log(store); // ta-daaa, Object!
    response.end(store);
});

答案 1 :(得分:1)

你有没有试过像:

...
response.end(JSON.stringify(store));
相关问题