我正在使用 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/