From b3a4ff03e27fde35ba666c0c8b16b6505d906ff6 Mon Sep 17 00:00:00 2001 From: Konstantin Baumann Date: Thu, 12 Nov 2015 11:16:57 +0100 Subject: [PATCH 1/2] uncompress the response body transparently if required --- lib/adapters/http.js | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/adapters/http.js b/lib/adapters/http.js index 7d11657..b0a7006 100644 --- a/lib/adapters/http.js +++ b/lib/adapters/http.js @@ -7,6 +7,7 @@ var transformData = require('./../helpers/transformData'); var http = require('http'); var https = require('https'); var url = require('url'); +var zlib = require('zlib'); var pkg = require('./../../package.json'); var Buffer = require('buffer').Buffer; @@ -59,12 +60,27 @@ module.exports = function httpAdapter(resolve, reject, config) { // Create the request var transport = parsed.protocol === 'https:' ? https : http; var req = transport.request(options, function (res) { + + // uncompress the response body transparently if required + var stream = res; + switch(res.headers['content-encoding']) { + case 'gzip': + case 'compress': + case 'deflate': { + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + } + } + var responseBuffer = []; - res.on('data', function (chunk) { + stream.on('data', function (chunk) { responseBuffer.push(chunk); }); - res.on('end', function () { + stream.on('end', function () { var data = Buffer.concat(responseBuffer); if (config.responseType !== 'arraybuffer') { data = data.toString('utf8'); From 32dfc1d9e06b76663107a385c9d96c3c8fd11628 Mon Sep 17 00:00:00 2001 From: Konstantin Baumann Date: Thu, 12 Nov 2015 11:34:07 +0100 Subject: [PATCH 2/2] add test case for `transparent decompression` for `content-encoding` being set in the response headers --- test/unit/adapters/http.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/unit/adapters/http.js b/test/unit/adapters/http.js index 38ee7a5..34caefe 100644 --- a/test/unit/adapters/http.js +++ b/test/unit/adapters/http.js @@ -1,5 +1,6 @@ var axios = require('../../../index'); var http = require('http'); +var zlib = require('zlib'); var server; module.exports = { @@ -27,6 +28,29 @@ module.exports = { }); }, + testTransparentGunzip: function (test) { + var data = { + firstName: 'Fred', + lastName: 'Flintstone', + emailAddr: 'fred@example.com' + }; + + zlib.gzip(JSON.stringify(data), function(err, zipped) { + + server = http.createServer(function (req, res) { + res.setHeader('Content-Type', 'application/json;charset=utf-8'); + res.setHeader('Content-Encoding', 'gzip'); + res.end(zipped); + }).listen(4444, function () { + axios.get('http://localhost:4444/').then(function (res) { + test.deepEqual(res.data, data); + test.done(); + }); + }); + + }); + }, + testUTF8: function (test) { var str = Array(100000).join('ж');