diff --git a/README.md b/README.md index 0e3426f..c9f643a 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,10 @@ These are the available config options for making requests. Only the `url` is re // as well as 'GET' downloads progress: function(progressEvent) { // Do whatever you want with the native progress event - } + }, + + // `maxContentLength` defines the max size of the http response content allowed + maxContentLength: 2000 } ``` diff --git a/lib/adapters/http.js b/lib/adapters/http.js index 4befc07..3179251 100644 --- a/lib/adapters/http.js +++ b/lib/adapters/http.js @@ -90,6 +90,11 @@ module.exports = function httpAdapter(resolve, reject, config) { var responseBuffer = []; stream.on('data', function handleStreamData(chunk) { responseBuffer.push(chunk); + + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { + reject(new Error('maxContentLength size of ' + config.maxContentLength + ' exceeded')); + } }); stream.on('end', function handleStreamEnd() { diff --git a/lib/defaults.js b/lib/defaults.js index 6a51c2c..45910c8 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -59,5 +59,7 @@ module.exports = { timeout: 0, xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1 }; diff --git a/test/unit/adapters/http.js b/test/unit/adapters/http.js index 4bfcc7b..b7f2086 100644 --- a/test/unit/adapters/http.js +++ b/test/unit/adapters/http.js @@ -127,4 +127,31 @@ module.exports = { }); }); }, + + testMaxContentLength: function(test) { + var str = Array(100000).join('ж'); + + server = http.createServer(function (req, res) { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + res.end(str); + }).listen(4444, function () { + var success = false, failure = false, error; + + axios.get('http://localhost:4444/', { + maxContentLength: 2000 + }).then(function (res) { + success = true; + }).catch(function (res) { + error = res; + failure = true; + }); + + setTimeout(function () { + test.equal(success, false, 'request should not succeed'); + test.equal(failure, true, 'request should fail'); + test.equal(error.message, 'maxContentLength size of 2000 exceeded'); + test.done(); + }, 100); + }); + } };