Nodejsstream(错误:发送后无法设置标题)

我正在尝试从braintree服务器上构build一个API。 参考这个文档https://developers.braintreepayments.com/javascript+node/reference/general/result-handling/search-results

要从服务器访问所有事务,我必须返回一个节点stream

app.get('/project', function(req, res) { if(req.user) { var stream = gateway.transaction.search(function (search) { search.customerId().is(req.user.id); }); stream.on("ready", function () { console.log(stream.searchResponse); }); stream.on("data", function (data) { res.json(data) // can't set headers after they are sent. }); } }); 

我知道一个stream以块的forms返回数据,所以上面的res.json()很可能被多次调用导致Error: Can't set headers after they are sent

所以我的问题是我怎么能发送数据到客户端在一个块? nodejsstream是混淆我,我会读更多的关于它,但了解如何将数据发送到客户端而不重新发送标头将是很好的。

Solutions Collecting From Web of "Nodejsstream(错误:发送后无法设置标题)"

除非正在读取的datastream处于对象模式,否则不应对data事件做出任何假设。 您可以获得一个data事件或一百个(取决于当然的input大小),因为TCP是一个stream。

你可能想要的是这样的事情(假设stream不处于对象模式):

 app.get('/project', function(req, res) { if(req.user) { var stream = gateway.transaction.search(function (search) { search.customerId().is(req.user.id); }); stream.on("ready", function () { console.log(stream.searchResponse); }); var buf = ''; stream.on("data", function (data) { buf += data; }); stream.on("end", function() { res.setHeader('Content-Type', 'application/json'); res.send(buf); }); } }); 

或者只是将stream传递给响应:

 app.get('/project', function(req, res) { if(req.user) { var stream = gateway.transaction.search(function (search) { search.customerId().is(req.user.id); }); stream.on("ready", function () { console.log(stream.searchResponse); }); res.setHeader('Content-Type', 'application/json'); stream.pipe(res); } }); 

对于一个对象stream你可能会这样做:

 app.get('/project', function(req, res) { if(req.user) { var stream = gateway.transaction.search(function (search) { search.customerId().is(req.user.id); }); stream.on("ready", function () { console.log(stream.searchResponse); }); var result = []; stream.on("data", function (data) { result.push(data); }); stream.on("end", function() { res.json(result); }); } });