Reputation: 81
I have this Java code
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.setHeader("Accept-Encoding", "gzip");
// only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
and this in node.js
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");
if ( request.method === 'POST' ) {
// the body of the POST is JSON payload.
request.pipe(process.stdout);
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
Im using the pipe to write everything in the console to be sure that i receive the data. What i actually want is to parse the data back to JSON and then save it in a array. How do i get the data from the request? Does anyone have an code example?
Thanks
Upvotes: 0
Views: 916
Reputation: 1108
try to use the following concept in your code
response.on('data', function (chunk)
{
var data = chunk.toString();
var data_val = JSON.parse(data)
});
Upvotes: 0
Reputation: 26199
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
console.log("Entering");
if ( request.method === 'POST' ) {
// the body of the POST is JSON payload.
request.pipe(process.stdout);
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
try {
data = JSON.parse(data);
} catch (e) {
console.log(e);
}
});
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
Upvotes: 1