javascript - Is there a way to synchronously read the contents of HTTP request body in node.js? -



javascript - Is there a way to synchronously read the contents of HTTP request body in node.js? -

so sending http post request node.js http server that's running locally. wish extract json object http body, , utilize info holds stuff on server side.

here client app, issues request:

var requester = require('request'); requester.post( 'http://localhost:1337/', {body:json.stringify({"someelement":"somevalue"})}, function(error, response, body){ if(!error) { console.log(body); } else { console.log(error+response+body); console.log(body); } } );

here's server supposed receive request:

http.createserver(function (req, res) { var chunk = {}; req.on('data', function (chunk) { chunk = json.parse(chunk); }); if(chunk.someelement) { console.log(chunk); // stuff } else { // study error } res.writehead(200, {'content-type': 'text/plain'}); res.end('done work \n'); }).listen(1337, '127.0.0.1'); console.log('server running @ http://127.0.0.1:1337/');

now issue is, since req.on() function has callback extracts post info asynchronously, seems if(chunk.someelement) clause evaluated before done, , goes else clause , unable @ all.

is there simpler way handle issue (by simpler, mean: not using other fancy libraries or modules, pure node)? is there synchronous function performs same tasks req.on() , returns contents of body before if(chunk.someelement) check?

you need wait , buffer request , parse/use json on request's 'end' event instead because there no guarantee info received single chunk:

http.createserver(function (req, res) { var buffer = ''; req.on('data', function (chunk) { buffer += chunk; }).on('end', function() { var result; seek { result = json.parse(buffer); } grab (ex) { res.writehead(400); homecoming res.end('bad json'); } if (result && result.someelement) { console.log(chunk); // stuff } else { // study error } res.writehead(200, {'content-type': 'text/plain'}); res.end('done work \n'); }).setencoding('utf8'); }).listen(1337, '127.0.0.1'); console.log('server running @ http://127.0.0.1:1337/');

javascript node.js http post

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -