per*_*ery 0 javascript post http 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);
}
}
);
Run Code Online (Sandbox Code Playgroud)
这是应该接收该请求的服务器:
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/');
Run Code Online (Sandbox Code Playgroud)
现在的问题是,由于req.on()具有回调的函数异步提取 POST 数据,似乎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/');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1597 次 |
| 最近记录: |