[英]Is there a way to synchronously read the contents of HTTP request body in node.js?
因此,我正在向本地运行的node.js HTTP服务器发送HTTP POST请求。 我希望从HTTP主体中提取JSON对象,并使用其持有的数据在服务器端执行一些操作。
这是我的客户端应用程序,它发出请求:
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);
}
}
);
这是应该接收该请求的服务器:
http.createServer(function (req, res) {
var chunk = {};
req.on('data', function (chunk) {
chunk = JSON.parse(chunk);
});
if(chunk.someElement)
{
console.log(chunk);
// do some stuff
}
else
{
// report error
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Done with work \n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
现在的问题是,由于具有回调的req.on()
函数以异步方式提取POST数据,因此好像if(chunk.someElement)
子句在执行之前if(chunk.someElement)
被求值,因此它总是转到else子句和我什么也做不了。
req.on()
相同的任务,并在执行if(chunk.someElement)
检查之前返回主体的内容? 您需要等待并缓冲请求,然后在请求的“结束”事件上解析/使用JSON,因为无法保证所有数据都将作为单个块接收:
http.createServer(function (req, res) {
var buffer = '';
req.on('data', function (chunk) {
buffer += chunk;
}).on('end', function() {
var result;
try {
result = JSON.parse(buffer);
} catch (ex) {
res.writeHead(400);
return res.end('Bad JSON');
}
if (result && result.someElement)
{
console.log(chunk);
// do some stuff
}
else
{
// report error
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Done with work \n');
}).setEncoding('utf8');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.