How do I get the value of json data sent from client with ajax in node.js? I tried so many examples and q&a but still it's not working. I'm totally new to node.js so my question could be dumb. I got my codes below. Please kindly point me out where and what are wrong. I'm totally lost.
What i need is the value "TEST" from data of the json.
I tried req.body.data
Client [html]
$.ajax({
type:"POST",
url: 'http://localhost:8080/getFromDB',
//data:JSON.stringify({"sql":"SELECT * FROM Track"}),
data: '{"data": "TEST"}',
success:function(data) {
$('#disco').html(data);
},
error:function() {
$('#disco').html('Error connecting to the server.');
}
});
node.js
var app = module.exports = require('appjs');
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var path = url.parse(req.url).pathname;
var value;
if(path == "/getFromDB") {
// req = JSON.parse(req);
// var testshit1 = parser(req.data);
req.on('data', function (data) {
value = JSON.parse(data);
});
// ------- e.o test -------
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
res.end('value = ' + value);
}
}).listen(8080);