【问题标题】:Receive data at node.js server from Ajax call in Object format从 Ajax 调用以 Object 格式在 node.js 服务器接收数据
【发布时间】:2013-07-17 10:20:56
【问题描述】:

我正在使用 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);
    });
}

问题:当我在请求结束函数中安慰“存储”变量时,我得到这样的结果:

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

我只想在服务器端使用我在 Ajax 'data' 参数中发送的相同数据。我也试过了,queryString.parse, JSON.parse() 但没有帮助。我只希望我的输出为:

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

【问题讨论】:

    标签: ajax json node.js


    【解决方案1】:

    你需要告诉 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);
    });
    

    【讨论】:

    • 只是试了一下,不工作,仍然在他的 request.on('end', function).... (name=Manish&address%5Bcity%5D=BBSR&address% 5Bcountry%5D=IN])
    • 查看更新的答案,刚刚在data 周围添加了JSON.stringify()。这必须起作用,这就是骨干的作用......
    【解决方案2】:

    您是否尝试过类似的方法:

    ...
    response.end(JSON.stringify(store));
    

    【讨论】:

    • 什么也没发生,只是返回相同的字符串 ("name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN") 并在其周围加上引号。无论如何,我不需要客户端生成的对象,我只想在服务器端操作字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多