2013-10-17 14 views
25

Sto tentando di inviare una semplice richiesta POST HTTP, recuperare il corpo della risposta. Segue il mio codice. RicevoControllo errato dell'intestazione quando si utilizza zlib in node.js

Error: Incorrect header check

all'interno del metodo "zlib.gunzip". Sono nuovo di node.js e apprezzo qualsiasi aiuto.

;

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

Potreste pubblicare il tuo stack trace? – hexacyanide

+1

Un piccolo consiglio: quando inserisci il codice, usa gli spazi al posto delle schede. Rende molto più facile la formattazione. – thtsigma

+0

Sto usando zlib.unzip invece zlib.gunzip – Evgenii

risposta

12

response.on('data', ...) può accettare un Buffer, non solo le stringhe semplici. Quando si concatena, si sta convertendo in stringa in modo errato, e in seguito non è possibile eseguire il gunzip. Sono disponibili 2 opzioni:

1) Raccogliere tutti i buffer in un array e nell'evento end concatenarli utilizzando Buffer.concat(). Quindi chiama gunzip sul risultato.

2) Utilizzare .pipe() e inviare la risposta a un oggetto gunzip, collegando l'output di questo a uno stream di file oa una stringa/stringa di buffer se si desidera il risultato in memoria.

Entrambe le opzioni (1) e (2) sono discussi qui: http://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression

Problemi correlati