2013-10-17 4 views
25

간단한 HTTP POST 요청을 보내려 고 응답 본문을 검색하려고합니다. 다음 코드는 내 코드입니다. 나는 "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.gunzip 대신 zlib.unzip을 사용하고 있습니다. – Evgenii

답변

12

response.on('data', ...)은 일반 문자열뿐만 아니라 Buffer을 허용 할 수 있습니다. 연결시 문자열로 잘못 변환되고 나중에 gunzip 할 수 없습니다. 다음과 같은 두 가지 옵션이 있습니다.

1) 배열의 모든 버퍼를 수집하고 end 이벤트에서 Buffer.concat()을 사용하여 병합합니다. 그런 다음 gunzip을 호출하십시오.

2) .pipe()을 사용하고 결과를 메모리에 넣으려면 gunzip 개체에 대한 응답을 파이핑하여 파일 스트림이나 문자열/버퍼 문자열로 파이프하십시오.

두 옵션 (1)과 (2) 여기에서 설명은 : http://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression

관련 문제