2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-02 16:04:10 +03:00

Resolving merge conflicts

This commit is contained in:
Nick Uraltsev
2016-05-18 19:44:21 -07:00
22 changed files with 507 additions and 167 deletions
+3
View File
@@ -6,8 +6,11 @@ node_modules/
sandbox/
test/
bower.json
CODE_OF_CONDUCT.md
COLLABORATOR_GUIDE.md
CONTRIBUTING.md
COOKBOOK.md
ECOSYSTEM.md
Gruntfile.js
karma.conf.js
webpack.*.js
+23
View File
@@ -1,5 +1,28 @@
# Changelog
### 0.11.1 (May 17, 2016)
- Fixing IE CORS support ([#313](https://github.com/mzabriskie/axios/pull/313))
- Fixing detection of `FormData` ([#325](https://github.com/mzabriskie/axios/pull/325))
- Adding `Axios` class to exports ([#321](https://github.com/mzabriskie/axios/pull/321))
### 0.11.0 (Apr 26, 2016)
- Adding support for Stream with HTTP adapter ([#296](https://github.com/mzabriskie/axios/pull/296))
- Adding support for custom HTTP status code error ranges ([#308](https://github.com/mzabriskie/axios/pull/308))
- Fixing issue with ArrayBuffer ([#299](https://github.com/mzabriskie/axios/pull/299))
### 0.10.0 (Apr 20, 2016)
- Fixing issue with some requests sending `undefined` instead of `null` ([#250](https://github.com/mzabriskie/axios/pull/250))
- Fixing basic auth for HTTP adapter ([#252](https://github.com/mzabriskie/axios/pull/252))
- Fixing request timeout for XHR adapter ([#227](https://github.com/mzabriskie/axios/pull/227))
- Fixing IE8 support by using `onreadystatechange` instead of `onload` ([#249](https://github.com/mzabriskie/axios/pull/249))
- Fixing IE9 cross domain requests ([#251](https://github.com/mzabriskie/axios/pull/251))
- Adding `maxContentLength` option ([#275](https://github.com/mzabriskie/axios/pull/275))
- Fixing XHR support for WebWorker environment ([#279](https://github.com/mzabriskie/axios/pull/279))
- Adding request instance to response ([#200](https://github.com/mzabriskie/axios/pull/200))
### 0.9.1 (Jan 24, 2016)
- Improving handling of request timeout in node ([#124](https://github.com/mzabriskie/axios/issues/124))
+9
View File
@@ -0,0 +1,9 @@
# Ecosystem
This is a list of axios related libraries and resources. If you have a suggestion on what to add, please don't hesitate to submit a PR.
## Libraries
* [axios-response-logger](https://github.com/srph/axios-response-logger) - Axios interceptor which logs responses
* [axios-mock-adapter](https://github.com/ctimmerm/axios-mock-adapter) — Axios adapter that allows to easily mock requests
* [redux-axios-middleware](https://github.com/svrcekmichal/redux-axios-middleware) - Redux middleware for fetching data with axios HTTP client
+45 -13
View File
@@ -28,10 +28,10 @@ Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
## Installing
Using bower:
Using cdn:
```bash
$ bower install axios
```html
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
```
Using npm:
@@ -40,6 +40,12 @@ Using npm:
$ npm install axios
```
Using bower:
```bash
$ bower install axios
```
## Example
Performing a `GET` request
@@ -129,6 +135,7 @@ axios('/user/12345');
For convenience aliases have been provided for all supported request methods.
##### axios.request(config)
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
@@ -180,18 +187,18 @@ These are the available config options for making requests. Only the `url` is re
{
// `url` is the server URL that will be used for the request
url: '/user',
// `method` is the request method to be used when making the request
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an ArrayBuffer
// The last function in the array must return a string, an ArrayBuffer, or a Stream
transformRequest: [function (data) {
// Do whatever you want to transform the data
@@ -222,7 +229,7 @@ These are the available config options for making requests. Only the `url` is re
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
// When no `transformRequest` is set, must be a string, an ArrayBuffer, a hash, or a Stream
data: {
firstName: 'Fred'
},
@@ -250,7 +257,7 @@ These are the available config options for making requests. Only the `url` is re
}
// `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text'
// options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
@@ -261,12 +268,20 @@ These are the available config options for making requests. Only the `url` is re
// `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloads
progress: function(progressEvent) {
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
maxContentLength: 2000,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}
}
```
@@ -346,7 +361,7 @@ instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
});
```
## Interceptors
@@ -406,6 +421,16 @@ axios.get('/user/12345')
});
```
You can define a custom HTTP status code error range using the `validateStatus` config option.
```js
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
```
## Semver
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
@@ -423,6 +448,13 @@ import * as axios from 'axios';
axios.get('/user?ID=12345');
```
## Resources
* [Changelog](https://github.com/mzabriskie/axios/blob/master/CHANGELOG.md)
* [Ecosystem](https://github.com/mzabriskie/axios/blob/master/ECOSYSTEM.md)
* [Contributing Guide](https://github.com/mzabriskie/axios/blob/master/CONTRIBUTING.md)
* [Code of Conduct](https://github.com/mzabriskie/axios/blob/master/CODE_OF_CONDUCT.md)
## Credits
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.
+35 -35
View File
@@ -1,38 +1,38 @@
{
"name": "axios",
"main": "./dist/axios.js",
"version": "0.9.1",
"homepage": "https://github.com/mzabriskie/axios",
"authors": [
"Matt Zabriskie"
],
"description": "Promise based HTTP client for the browser and node.js",
"moduleType": [
"amd",
"globals"
],
"keywords": [
"xhr",
"http",
"ajax",
"promise",
"node"
],
"license": "MIT",
"ignore": [
"**/.*",
"*.iml",
"examples",
"lib",
"node_modules",
"sandbox",
"test",
"CONTRIBUTING.md",
"name": "axios",
"main": "./dist/axios.js",
"version": "0.11.1",
"homepage": "https://github.com/mzabriskie/axios",
"authors": [
"Matt Zabriskie"
],
"description": "Promise based HTTP client for the browser and node.js",
"moduleType": [
"amd",
"globals"
],
"keywords": [
"xhr",
"http",
"ajax",
"promise",
"node"
],
"license": "MIT",
"ignore": [
"**/.*",
"*.iml",
"examples",
"lib",
"node_modules",
"sandbox",
"test",
"CONTRIBUTING.md",
"COOKBOOK.md",
"Gruntfile.js",
"index.js",
"karma.conf.js",
"package.json",
"Gruntfile.js",
"index.js",
"karma.conf.js",
"package.json",
"webpack.*.js"
]
}
]
}
+126 -45
View File
@@ -1,4 +1,4 @@
/* axios v0.9.1 | (c) 2016 by Matt Zabriskie */
/* axios v0.11.1 | (c) 2016 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
@@ -66,10 +66,10 @@ return /******/ (function(modules) { // webpackBootstrap
var defaults = __webpack_require__(2);
var utils = __webpack_require__(3);
var dispatchRequest = __webpack_require__(4);
var InterceptorManager = __webpack_require__(12);
var isAbsoluteURL = __webpack_require__(13);
var combineURLs = __webpack_require__(14);
var bind = __webpack_require__(15);
var InterceptorManager = __webpack_require__(13);
var isAbsoluteURL = __webpack_require__(14);
var combineURLs = __webpack_require__(15);
var bind = __webpack_require__(16);
var transformData = __webpack_require__(8);
function Axios(defaultConfig) {
@@ -141,22 +141,22 @@ return /******/ (function(modules) { // webpackBootstrap
var defaultInstance = new Axios(defaults);
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
module.exports.Axios = Axios;
// Expose properties from defaultInstance
axios.defaults = defaultInstance.defaults;
axios.interceptors = defaultInstance.interceptors;
// Factory for creating new instances
axios.create = function create(defaultConfig) {
return new Axios(defaultConfig);
};
// Expose defaults
axios.defaults = defaultInstance.defaults;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(16);
// Expose interceptors
axios.interceptors = defaultInstance.interceptors;
axios.spread = __webpack_require__(17);
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
@@ -197,11 +197,8 @@ return /******/ (function(modules) { // webpackBootstrap
};
module.exports = {
transformRequest: [function transformResponseJSON(data, headers) {
if (utils.isFormData(data)) {
return data;
}
if (utils.isArrayBuffer(data)) {
transformRequest: [function transformRequest(data, headers) {
if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data)) {
return data;
}
if (utils.isArrayBufferView(data)) {
@@ -225,7 +222,7 @@ return /******/ (function(modules) { // webpackBootstrap
return data;
}],
transformResponse: [function transformResponseJSON(data) {
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
data = data.replace(PROTECTION_PREFIX, '');
@@ -248,7 +245,13 @@ return /******/ (function(modules) { // webpackBootstrap
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
@@ -291,7 +294,7 @@ return /******/ (function(modules) { // webpackBootstrap
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString.call(val) === '[object FormData]';
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
@@ -380,6 +383,26 @@ return /******/ (function(modules) { // webpackBootstrap
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Trim excess whitespace off the beginning and end of a string
*
@@ -495,6 +518,8 @@ return /******/ (function(modules) { // webpackBootstrap
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
@@ -553,7 +578,8 @@ return /******/ (function(modules) { // webpackBootstrap
var parseHeaders = __webpack_require__(7);
var transformData = __webpack_require__(8);
var isURLSameOrigin = __webpack_require__(9);
var btoa = window.btoa || __webpack_require__(10);
var btoa = (typeof window !== 'undefined' && window.btoa) || __webpack_require__(10);
var settle = __webpack_require__(11);
module.exports = function xhrAdapter(resolve, reject, config) {
var requestData = config.data;
@@ -564,11 +590,18 @@ return /******/ (function(modules) { // webpackBootstrap
}
var request = new XMLHttpRequest();
var loadEvent = 'onreadystatechange';
var xDomain = false;
// For IE 8/9 CORS support
// Only supports POST and GET calls and doesn't returns the response headers.
if (window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
// DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
if (("production") !== 'test' && typeof window !== 'undefined' && window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
request = new window.XDomainRequest();
loadEvent = 'onload';
xDomain = true;
request.onprogress = function handleProgress() {};
request.ontimeout = function handleTimeout() {};
}
// HTTP basic authentication
@@ -584,13 +617,20 @@ return /******/ (function(modules) { // webpackBootstrap
request.timeout = config.timeout;
// Listen for ready state
request.onload = function handleLoad() {
if (!request) {
request[loadEvent] = function handleLoad() {
if (!request || (request.readyState !== 4 && !xDomain)) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
if (request.status === 0) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: transformData(
responseData,
@@ -601,14 +641,11 @@ return /******/ (function(modules) { // webpackBootstrap
status: request.status === 1223 ? 204 : request.status,
statusText: request.status === 1223 ? 'No Content' : request.statusText,
headers: responseHeaders,
config: config
config: config,
request: request
};
// Resolve or reject the Promise based on the status
((response.status >= 200 && response.status < 300) ||
(!('status' in request) && response.responseText) ?
resolve :
reject)(response);
settle(resolve, reject, response);
// Clean up request
request = null;
@@ -624,11 +661,22 @@ return /******/ (function(modules) { // webpackBootstrap
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var err = new Error('timeout of ' + config.timeout + 'ms exceeded');
err.timeout = config.timeout;
err.code = 'ECONNABORTED';
reject(err);
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(11);
var cookies = __webpack_require__(12);
// Add xsrf header
var xsrfValue = config.withCredentials || isURLSameOrigin(config.url) ?
@@ -669,8 +717,17 @@ return /******/ (function(modules) { // webpackBootstrap
}
}
if (utils.isArrayBuffer(requestData)) {
requestData = new DataView(requestData);
// Handle progress if needed
if (config.progress) {
if (config.method === 'post' || config.method === 'put') {
request.upload.addEventListener('progress', config.progress);
} else if (config.method === 'get') {
request.addEventListener('progress', config.progress);
}
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
@@ -904,12 +961,12 @@ return /******/ (function(modules) { // webpackBootstrap
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
function E() {
this.message = 'String contains an invalid character';
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.code = 5;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
E.prototype = new Error;
E.prototype.code = 5;
E.prototype.name = 'InvalidCharacterError';
function btoa(input) {
var str = String(input);
@@ -926,7 +983,7 @@ return /******/ (function(modules) { // webpackBootstrap
) {
charCode = str.charCodeAt(idx += 3 / 4);
if (charCode > 0xFF) {
throw new InvalidCharacterError('INVALID_CHARACTER_ERR: DOM Exception 5');
throw new E();
}
block = block << 8 | charCode;
}
@@ -938,6 +995,30 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 11 */
/***/ function(module, exports) {
'use strict';
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
// Note: status is not exposed by XDomainRequest
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(response);
}
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
@@ -996,7 +1077,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 12 */
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
@@ -1054,7 +1135,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 13 */
/* 14 */
/***/ function(module, exports) {
'use strict';
@@ -1074,7 +1155,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 14 */
/* 15 */
/***/ function(module, exports) {
'use strict';
@@ -1092,7 +1173,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 15 */
/* 16 */
/***/ function(module, exports) {
'use strict';
@@ -1109,7 +1190,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ },
/* 16 */
/* 17 */
/***/ function(module, exports) {
'use strict';
+1 -1
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+40 -37
View File
@@ -9,6 +9,7 @@ var url = require('url');
var zlib = require('zlib');
var pkg = require('./../../package.json');
var Buffer = require('buffer').Buffer;
var settle = require('../helpers/settle');
/*eslint consistent-return:0*/
module.exports = function httpAdapter(resolve, reject, config) {
@@ -24,13 +25,13 @@ module.exports = function httpAdapter(resolve, reject, config) {
headers['User-Agent'] = 'axios/' + pkg.version;
}
if (data) {
if (data && !utils.isStream(data)) {
if (utils.isArrayBuffer(data)) {
data = new Buffer(new Uint8Array(data));
} else if (utils.isString(data)) {
data = new Buffer(data, 'utf-8');
} else {
return reject(new Error('Data after transformation must be a string or an ArrayBuffer'));
return reject(new Error('Data after transformation must be a string, an ArrayBuffer, or a Stream'));
}
// Add Content-Length header if data exists
@@ -93,44 +94,42 @@ module.exports = function httpAdapter(resolve, reject, config) {
break;
}
var responseBuffer = [];
stream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
var response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
request: req
};
// 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'));
}
});
if (config.responseType === 'stream') {
response.data = stream;
settle(resolve, reject, response);
} else {
var responseBuffer = [];
stream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
stream.on('error', function handleStreamError(err) {
if (aborted) return;
reject(err);
});
// 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() {
var d = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
d = d.toString('utf8');
}
var response = {
data: transformData(
d,
res.headers,
config.transformResponse
),
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
request: req
};
stream.on('error', function handleStreamError(err) {
if (aborted) return;
reject(err);
});
// Resolve or reject the Promise based on the status
(res.statusCode >= 200 && res.statusCode < 300 ?
resolve :
reject)(response);
});
stream.on('end', function handleStreamEnd() {
var responseData = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString('utf8');
}
response.data = transformData(responseData, res.headers, config.transformResponse);
settle(resolve, reject, response);
});
}
});
// Handle errors
@@ -152,5 +151,9 @@ module.exports = function httpAdapter(resolve, reject, config) {
}
// Send the request
req.end(data);
if (utils.isStream(data)) {
data.pipe(req);
} else {
req.end(data);
}
};
+4 -14
View File
@@ -6,6 +6,7 @@ var parseHeaders = require('./../helpers/parseHeaders');
var transformData = require('./../helpers/transformData');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var btoa = (typeof window !== 'undefined' && window.btoa) || require('./../helpers/btoa');
var settle = require('../helpers/settle');
module.exports = function xhrAdapter(resolve, reject, config) {
var requestData = config.data;
@@ -26,6 +27,8 @@ module.exports = function xhrAdapter(resolve, reject, config) {
request = new window.XDomainRequest();
loadEvent = 'onload';
xDomain = true;
request.onprogress = function handleProgress() {};
request.ontimeout = function handleTimeout() {};
}
// HTTP basic authentication
@@ -40,10 +43,6 @@ module.exports = function xhrAdapter(resolve, reject, config) {
// Set the request timeout in MS
request.timeout = config.timeout;
// For IE 9 CORS support.
request.onprogress = function handleProgress() {};
request.ontimeout = function handleTimeout() {};
// Listen for ready state
request[loadEvent] = function handleLoad() {
if (!request || (request.readyState !== 4 && !xDomain)) {
@@ -73,11 +72,7 @@ module.exports = function xhrAdapter(resolve, reject, config) {
request: request
};
// Resolve or reject the Promise based on the status
((response.status >= 200 && response.status < 300) ||
(!('status' in request) && request.responseText) ?
resolve :
reject)(response);
settle(resolve, reject, response);
// Clean up request
request = null;
@@ -158,11 +153,6 @@ module.exports = function xhrAdapter(resolve, reject, config) {
}
}
// Format request data
if (utils.isArrayBuffer(requestData)) {
requestData = new DataView(requestData);
}
if (requestData === undefined) {
requestData = null;
}
+4
View File
@@ -78,6 +78,10 @@ Axios.prototype.request = function request(config) {
var defaultInstance = new Axios(defaults);
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
axios.request = bind(Axios.prototype.request, defaultInstance);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose properties from defaultInstance
axios.defaults = defaultInstance.defaults;
+3 -3
View File
@@ -15,12 +15,12 @@ module.exports = function dispatchRequest(config) {
if (typeof config.adapter === 'function') {
// For custom adapter support
adapter = config.adapter;
} else if (typeof process !== 'undefined') {
// For node use HTTP adapter
adapter = require('../adapters/http');
} else if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('../adapters/xhr');
} else if (typeof process !== 'undefined') {
// For node use HTTP adapter
adapter = require('../adapters/http');
}
if (typeof adapter === 'function') {
+8 -7
View File
@@ -8,11 +8,8 @@ var DEFAULT_CONTENT_TYPE = {
};
module.exports = {
transformRequest: [function transformRequestJSON(data, headers) {
if (utils.isFormData(data)) {
return data;
}
if (utils.isArrayBuffer(data)) {
transformRequest: [function transformRequest(data, headers) {
if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data)) {
return data;
}
if (utils.isArrayBufferView(data)) {
@@ -36,7 +33,7 @@ module.exports = {
return data;
}],
transformResponse: [function transformResponseJSON(data) {
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
data = data.replace(PROTECTION_PREFIX, '');
@@ -61,5 +58,9 @@ module.exports = {
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
+18
View File
@@ -0,0 +1,18 @@
'use strict';
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
// Note: status is not exposed by XDomainRequest
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(response);
}
};
+23 -1
View File
@@ -33,7 +33,7 @@ function isArrayBuffer(val) {
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString.call(val) === '[object FormData]';
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
@@ -122,6 +122,26 @@ function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Trim excess whitespace off the beginning and end of a string
*
@@ -237,6 +257,8 @@ module.exports = {
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "axios",
"version": "0.9.1",
"version": "0.11.1",
"description": "Promise based HTTP client for the browser and node.js",
"main": "index.js",
"scripts": {
+1
View File
@@ -1,5 +1,6 @@
describe('static api', function () {
it('should have request method helpers', function () {
expect(typeof axios.request).toEqual('function');
expect(typeof axios.get).toEqual('function');
expect(typeof axios.head).toEqual('function');
expect(typeof axios.delete).toEqual('function');
+75
View File
@@ -0,0 +1,75 @@
var settle = require('../../../lib/helpers/settle');
describe('helpers::settle', function() {
var resolve;
var reject;
beforeEach(function() {
resolve = jasmine.createSpy('resolve');
reject = jasmine.createSpy('reject');
});
it('should resolve promise if status is not set', function() {
var response = {
config: {
validateStatus: function() {
return true;
}
}
};
settle(resolve, reject, response);
expect(resolve).toHaveBeenCalledWith(response);
expect(reject).not.toHaveBeenCalled();
});
it('should resolve promise if validateStatus is not set', function() {
var response = {
status: 500,
config: {
}
};
settle(resolve, reject, response);
expect(resolve).toHaveBeenCalledWith(response);
expect(reject).not.toHaveBeenCalled();
});
it('should resolve promise if validateStatus returns true', function() {
var response = {
status: 500,
config: {
validateStatus: function() {
return true;
}
}
};
settle(resolve, reject, response);
expect(resolve).toHaveBeenCalledWith(response);
expect(reject).not.toHaveBeenCalled();
});
it('should reject promise if validateStatus returns false', function() {
var response = {
status: 500,
config: {
validateStatus: function() {
return false;
}
}
};
settle(resolve, reject, response);
expect(resolve).not.toHaveBeenCalled();
expect(reject).toHaveBeenCalledWith(response);
});
it('should pass status to validateStatus', function() {
var validateStatus = jasmine.createSpy('validateStatus');
var response = {
status: 500,
config: {
validateStatus: validateStatus
}
};
settle(resolve, reject, response);
expect(validateStatus).toHaveBeenCalledWith(500);
});
});
+50 -4
View File
@@ -55,6 +55,52 @@ describe('requests', function () {
.then(finish, finish);
});
it('should reject when validateStatus returns false', function (done) {
var resolveSpy = jasmine.createSpy('resolve');
var rejectSpy = jasmine.createSpy('reject');
axios('/foo', {
validateStatus: function (status) {
return status !== 500;
}
}).then(resolveSpy)
.catch(rejectSpy)
.then(function () {
expect(resolveSpy).not.toHaveBeenCalled();
expect(rejectSpy).toHaveBeenCalled();
done();
});
getAjaxRequest().then(function (request) {
request.respondWith({
status: 500
});
});
});
it('should resolve when validateStatus returns true', function (done) {
var resolveSpy = jasmine.createSpy('resolve');
var rejectSpy = jasmine.createSpy('reject');
axios('/foo', {
validateStatus: function (status) {
return status === 500;
}
}).then(resolveSpy)
.catch(rejectSpy)
.then(function () {
expect(resolveSpy).toHaveBeenCalled();
expect(rejectSpy).not.toHaveBeenCalled();
done();
});
getAjaxRequest().then(function (request) {
request.respondWith({
status: 500
});
});
});
it('should make cross domian http request', function (done) {
var response;
@@ -71,7 +117,7 @@ describe('requests', function () {
'Content-Type': 'application/json'
}
});
setTimeout(function () {
expect(response.data.foo).toEqual('bar');
expect(response.status).toEqual(200);
@@ -164,7 +210,7 @@ describe('requests', function () {
axios.post('/foo', input.buffer);
getAjaxRequest().then(function (request) {
var output = new Int8Array(request.params.buffer);
var output = new Int8Array(request.params);
expect(output.length).toEqual(2);
expect(output[0]).toEqual(1);
expect(output[1]).toEqual(2);
@@ -186,7 +232,7 @@ describe('requests', function () {
axios.post('/foo', input);
getAjaxRequest().then(function (request) {
var output = new Int8Array(request.params.buffer);
var output = new Int8Array(request.params);
expect(output.length).toEqual(2);
expect(output[0]).toEqual(1);
expect(output[1]).toEqual(2);
@@ -200,7 +246,7 @@ describe('requests', function () {
done();
return;
}
var response;
function str2ab(str) {
+11 -1
View File
@@ -1,4 +1,5 @@
var utils = require('../../../lib/utils');
var Stream = require('stream');
describe('utils::isX', function () {
it('should validate Array', function () {
@@ -67,5 +68,14 @@ describe('utils::isX', function () {
expect(utils.isDate(new Date())).toEqual(true);
expect(utils.isDate(Date.now())).toEqual(false);
});
});
it('should validate Function', function () {
expect(utils.isFunction(function () {})).toEqual(true);
expect(utils.isFunction('function')).toEqual(false);
});
it('should validate Stream', function () {
expect(utils.isStream(new Stream.Readable())).toEqual(true);
expect(utils.isStream({ foo: 'bar' })).toEqual(false);
});
});
+24 -2
View File
@@ -2,6 +2,7 @@ var axios = require('../../../index');
var http = require('http');
var url = require('url');
var zlib = require('zlib');
var fs = require('fs');
var server;
module.exports = {
@@ -127,7 +128,7 @@ module.exports = {
});
});
},
testMaxContentLength: function(test) {
var str = Array(100000).join('ж');
@@ -145,7 +146,7 @@ module.exports = {
error = res;
failure = true;
});
setTimeout(function () {
test.equal(success, false, 'request should not succeed');
test.equal(failure, true, 'request should fail');
@@ -153,5 +154,26 @@ module.exports = {
test.done();
}, 100);
});
},
testStream: function(test) {
server = http.createServer(function (req, res) {
req.pipe(res);
}).listen(4444, function () {
axios.post('http://localhost:4444/',
fs.createReadStream(__filename), {
responseType: 'stream'
}).then(function (res) {
var stream = res.data;
var string = '';
stream.on('data', function (chunk) {
string += chunk.toString('utf8');
});
stream.on('end', function () {
test.equal(string, fs.readFileSync(__filename, 'utf8'));
test.done();
});
});
});
}
};