2013-10-17 13 views
25

我想發送一個簡單的HTTP POST請求,檢索響應body.Following是我的代碼。我得到不正確的標題在node.js中使用zlib時檢查

Error: Incorrect header check

裏面的「zlib.gunzip」方法。我是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