I have used this jquery ajax code to pass JSON:
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8080',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
I have used this node js code to parse JSON data:
http.createServer(function (request, response) {
response.writeHeader(200, {
"Content-Type": "text/plain"
});
response.writeHead(200, {"Content-Type":"text/plain"});
var theUrl = url.parse(request.url);
var queryObj = queryString.parse( theUrl.query );
var obj = JSON.parse( queryObj.jsonData);
console.log(obj[0].id)
response.write(String(obj[0].id))
response.end();
}).listen(8080,'127.0.0.1');
but it displays following error in console:
undefined:1
rn┴P║Eee
^
SyntaxError: Unexpected token u
at Object.parse (native)
at Server.<anonymous> (C:\node\nodejs\node_modules\17-8-12\tracker.js:79:22)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1610:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:91:29)
at Socket.ondata (http.js:1506:22)
at TCP.onread (net.js:374:27)
Then the code stops..
This isn't a direct answer for your issue but I would suggest checking out Express and the bodyParser middleware.
They you can do something like:
var express = require('express');
var app = express();
app.get('/', function(req, res){
console.log(req.query.jsonData);
res.send('return data here');
});
app.listen(8080);
This section:
response.writeHeader(200, {
"Content-Type": "text/plain"
});
response.writeHead(200, {"Content-Type":"text/plain"});
Seems garbled: is that your real code? If so, remove the first three lines. If that doesn't fix it, console.log
request.url
first, then queryObj.jsonData
and see if they're reasonable.