我使用Node后端(1)从Feedly Cloud请求API数据,(2)以JSON格式输出该数据,然后< strong>(3)从JS前端中检索它。
此问题仅涉及阶段(2)。
在尝试打印前端数据以进行检索时,我注意到Node在中途切断,留下格式错误的JSON。
我在编写响应内容之前尝试为Content-Length设置响应标头,以强制它打印整个内容。这有效,大约两次。但后来它开始大惊小怪了:
现在应用程序在功能运行时崩溃,声称我设置HTTP标头 AFTER 编写内容或输出到页面,只要我知道我是不
var http = require('http')
, authCode = 'xyz';
var FeedlyController = {
api: function(req, res) {
http.get({
host : "cloud.feedly.com",
path : "/v3/"+req.params.resource,
headers: { Authorization: "OAuth "+authCode }
}, function(response) {
response.on('data', function(json){
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(json, 'utf8')
});
res.write(json, 'UTF-8');
res.end();
});
});
}
}
module.exports = FeedlyController;
_http_outgoing.js:331
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:331:11)
at ServerResponse.res.setHeader (/Users/jan/Sites/proxenos/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:63:22)
at ServerResponse.<anonymous> (/Users/jan/Sites/proxenos/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:80:14)
at Array.forEach (native)
at ServerResponse.res.writeHead (/Users/jan/Sites/proxenos/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:79:28)
at IncomingMessage.<anonymous> (/Users/jan/Sites/proxenos/api/controllers/FeedlyController.js:12:19)
at IncomingMessage.EventEmitter.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:159:16)
at IncomingMessage.Readable.push (_stream_readable.js:126:10)
at HTTPParser.parserOnBody (_http_common.js:132:22)
答案 0 :(得分:4)
我怀疑您的数据事件多次触发(因为它是如何工作的,多个data
事件,然后是一个最终的end
事件。)
您可能想要阅读可读的流文档(response
对象是什么)
http://nodejs.org/api/stream.html#stream_class_stream_readable
我尝试将处理程序更改为:
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(json, 'utf8')
});
response.on('data', function(json){
res.write(json, 'UTF-8');
});
response.on('end', function(){
res.end();
});
虽然你可以通过它来管道:
response.pipe(res);
(而不是显式地监听数据和结束事件)