2013-10-17 26 views
25

簡単なHTTP POSTリクエストを送信しようとしていますが、レスポンスbodyを取得しています。 "zlib.gunzip"メソッドの中にnode.jsでzlibを使用しているときのヘッダチェックが正しくありません

Error: Incorrect header check

の方法があります。私はnode.jsが新しく、何か助けていただければ幸いです。

;

fireRequest: function() { 

    var rBody = ''; 
    var resBody = ''; 
    var contentLength; 

    var options = { 
     'encoding' : 'utf-8' 
    }; 

    rBody = fSystem.readFileSync('resources/im.json', options); 

    console.log('Loaded data from im.json ' + rBody); 

    contentLength = Buffer.byteLength(rBody, 'utf-8'); 

    console.log('Byte length of the request body ' + contentLength); 

    var httpOptions = { 
     hostname : 'abc.com', 
     path : '/path', 
     method : 'POST', 
     headers : { 
      'Authorization' : 'Basic VHJhZasfasNWEWFScsdfsNCdXllcjE6dHJhZGVjYXJk', 
      'Content-Type' : 'application/json; charset=UTF=8', 
      // 'Accept' : '*/*', 
      'Accept-Encoding' : 'gzip,deflate,sdch', 
      'Content-Length' : contentLength 
     } 
    }; 

    var postRequest = http.request(httpOptions, function(response) { 

     var chunks = ''; 
     console.log('Response received'); 
     console.log('STATUS: ' + response.statusCode); 
     console.log('HEADERS: ' + JSON.stringify(response.headers)); 
     // response.setEncoding('utf8'); 
     response.setEncoding(null); 
     response.on('data', function(res) { 
      chunks += res; 
     }); 

     response.on('end', function() { 
      var encoding = response.headers['content-encoding']; 
      if (encoding == 'gzip') { 

       zlib.gunzip(chunks, function(err, decoded) { 

        if (err) 
         throw err; 

        console.log('Decoded data: ' + decoded); 
       }); 
      } 
     }); 

    }); 

    postRequest.on('error', function(e) { 
     console.log('Error occured' + e); 
    }); 

    postRequest.write(rBody); 
    postRequest.end(); 

} 
+0

あなたのスタックトレースを投稿してもらえますか? – hexacyanide

+1

ちょっとしたヒント:コードを入力するときは、タブの代わりにスペースを使用してください。書式設定がはるかに簡単になります。 – thtsigma

+0

私はzlib.unzipを代わりに使用しています.zlib.gunzip – Evgenii

答えて

12

response.on('data', ...)Bufferだけではなく、プレーンな文字列を受け入れることができます。連結すると、文字列に正しく変換されず、後でgunzipできません。 2つのオプションがあります。

1)アレイ内のすべてのバッファーを収集し、endイベントでは、Buffer.concat()を使用してバッファーを連結します。その結果にgunzipを呼び出します。

2).pipe()を使用し、結果をメモリに格納する場合は、ファイルストリームまたは文字列/バッファ文字列のいずれかにその出力をパイプしてgunzipオブジェクトへの応答をパイプします。

両方のオプション(1)及び(2)ここで説明されていますhttp://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression

関連する問題