javascript - Node JSON 输出格式错误,无法设置 HTTP header : Content-Length to fix

标签 javascript node.js http express sails.js

问题

背景和意图

我正在使用 Node 后端(1) 从 Feedly Cloud 请求 API 数据,(2) 以 JSON 格式输出该数据,然后 (3) 从 JS 前端中检索它。

此问题仅与阶段(2)有关。

初始问题

在尝试打印数据供前端检索时,我注意到 Node 在中途中断,留下格式错误的 JSON。

尝试的解决方案

我尝试在写入响应内容之前为 Content-Length 设置响应 header ,以强制它打印整个内容。这奏效了,大约两次。但随后它开始大惊小怪:

持续失败

现在应用程序在函数运行时崩溃,声称我正在设置 HTTP header AFTER 写入内容或输出到页面,而据我所知我不是。 p>

代码

    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)

最佳答案

我怀疑您的数据事件触发了多次(因为它就是这样工作的,多个 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);

(而不是显式监听数据和结束事件)

关于javascript - Node JSON 输出格式错误,无法设置 HTTP header : Content-Length to fix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180846/

相关文章:

java - 加密/解密(使用 AES)大文件并通过 HTTP 传输

http - HTTP规范中,分隔cookie的字符串是什么?

javascript - 从计时器函数获取秒数到我的 View

javascript - 通过 http 向客户端发送文件时在 http header 中指定文件名

javascript - 覆盖 Electron 通知弹出窗口

node.js - 从配置文件快速路由

javascript - 如何在 azure 上部署和运行 Passport Express Node

javascript - 您可以在不使用服务器的情况下在本地生成 html 吗?

javascript - 如何在 NodeJs 中创建线程?

http - 如何通过 http 而不是 https 访问 glassfish 的控制台?