I am using Ajax call to post data from client side to node server and trying to receive data at server end, manipulate it(do some db query) and then return the 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 I am consoling "store" variable in request end function I am getting something like this:
name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN
I just want the same data at the server side what I sent in the Ajax 'data' parameter. I also tried, queryString.parse, JSON.parse() but no help. I just want my output as :
{name: "Manish", address: {city: "BBSR", country: "IN"}}
You need to tell jQuery that this is an 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, your request body will reach the server with the stringified JSON, so you'll be able to do the following:
request.on('end', function() {
store = JSON.parse(store);
console.log(store); // ta-daaa, Object!
response.end(store);
});
Have you tried something like:
...
response.end(JSON.stringify(store));