簡體   English   中英

節點JSON輸出格式錯誤,無法設置HTTP標頭:要修復的Content-Length

[英]Node JSON output malforms, unable to set HTTP Header: Content-Length to fix

問題

上下文和意圖

我正在使用Node后端來(1)向Feedly Cloud請求API數據, (2)以JSON格式輸出該數據,然后(3)從JS前端中檢索它。

該問題僅與階段(2)有關

創刊號

在嘗試打印數據以供前端檢索時,我注意到Node切斷了中間流,留下了格式錯誤的JSON。

嘗試的解決方案

在編寫響應內容之前,我嘗試為Content-Length設置響應標頭,以強制其打印整個內容。 那行得通,大約兩次。 但隨后開始大驚小怪:

持續失敗

現在,該應用程序在函數運行時崩潰,聲稱據我所知,我在寫內容或輸出到頁面設置了HTTP標頭。

編碼

    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_read

我會嘗試將您的處理程序更改為以下形式:

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);

(而不是顯式偵聽數據和結束事件)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM