如何管道POST请求

时间:2013-09-29 15:03:02

标签: node.js stream

我对如何管道一些数据感到有点困惑。

我有一些管道工作和链接,以至于我没有包含我想输入到请求POST的数据的输出流

var options = {
    host: 'localhost',
    port: 8529,
    path: '/_api/cursor',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': data.length
    }
}

var req = http.request(options);

我通常会动作'mystreams2.pipe(req)'但是如何设置'data.length'值呢?

(我使用的是streams2接口而不是旧的流格式)

1 个答案:

答案 0 :(得分:0)

假设您的缓冲区中没有大量数据,首先需要收集数据以查找其长度。

var source = /* a readable stream */;
var data = '';

source.on('data', function(chunk) {
  data += chunk;
});
source.on('end', function() {
  var options = {
    host: 'localhost',
    port: 8529,
    path: '/_api/cursor',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': data.length
    }
  };

  var req = http.request(options);
  req.end(data);
});
相关问题