json - Receive data at node.js server from Ajax call in Object format -
i using ajax call post data client side node server , trying receive data @ server end, manipulate it(do db query) , return response.
client side code :
$.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); });
server side :
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); }); }
problem : when consoling "store" variable in request end function getting this:
name=manish&address%5bcity%5d=bbsr&address%5bcountry%5d=in
i want same data @ server side sent in ajax 'data' parameter. tried, querystring.parse, json.parse() no help. want output :
{name: "manish", address: {city: "bbsr", country: "in"}}
you need tell jquery json request:
$.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); });
this way, request body reach server stringified json, you'll able following:
request.on('end', function() { store = json.parse(store); console.log(store); // ta-daaa, object! response.end(store); });
Comments
Post a Comment