ajax - 在 Node.js 服务器上从 Ajax 调用接收对象格式的数据

标签 ajax json node.js

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

客户端代码:

$.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"}}

最佳答案

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

关于ajax - 在 Node.js 服务器上从 Ajax 调用接收对象格式的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17723931/

相关文章:

php - 无法从表单获取数据到函数

javascript - javascript 上的 ajax 请求不起作用

java - 如何修复错误 json.JSONException : Index 1 out of range [0. .1)

php - PHP中的JSON数组三个mysql表

python - 使用python从ustream api解码json

javascript - AJAX 聊天应用程序的刷新率

node.js - Auth0 - 如何通过 Auth0 在本地主机上使用 mongoDB

node.js - 使用 oracle db 在 Node 中进行多个 SQL 查询

java - 避免在 Javascript 前端和 Java 后端重复验证代码?

javascript - 在php中提交表单后未收到值