以Object格式从Ajax调用接收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”variables时,我得到如下所示:
name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN
我只是想在服务器端的相同的数据,我在Ajax的“数据”参数发送。 我也试过,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); });
这样,您的请求主体将通过string化的JSON到达服务器,这样您就可以执行以下操作:
request.on('end', function() { store = JSON.parse(store); console.log(store); // ta-daaa, Object! response.end(store); });
你有没有试过类似的东西:
... response.end(JSON.stringify(store));