因此,我将 HTTP POST 请求发送到本地运行的 node.js HTTP 服务器。我希望从 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)
子句是在完成之前进行评估的,因此它总是转到 else 子句,而我根本无法执行任何操作。
- 有没有更简单的方法来处理这个问题(更简单,我的意思是:不 使用任何其他奇特的库或模块,只是纯 Node )?
- 有吗
一个同步函数,执行与
req.on()
相同的任务 在我执行之前返回正文的内容if(chunk.someElement)
检查?
最佳答案
您需要等待并缓冲请求,并在请求的“结束”事件上解析/使用 JSON,因为无法保证所有数据都将作为单个 block 接收:
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/');
关于javascript - 有没有办法在node.js中同步读取HTTP请求体的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356481/