mirror of
https://github.com/tenrok/axios.git
synced 2026-05-30 15:24:11 +03:00
Merge branch 'master' of github.com:mzabriskie/axios into xDomainRequestSupport
Conflicts: lib/adapters/xhr.js
This commit is contained in:
@@ -132,9 +132,34 @@ Helper functions for dealing with concurrent requests.
|
||||
##### axios.all(iterable)
|
||||
##### axios.spread(callback)
|
||||
|
||||
### Creating an instance
|
||||
|
||||
You can create a new instance of axios with a custom config.
|
||||
|
||||
##### axios.create([config])
|
||||
|
||||
```js
|
||||
var instance = axios.create({
|
||||
timeout: 1000,
|
||||
headers: {'X-Custom-Header': 'foobar'}
|
||||
});
|
||||
```
|
||||
|
||||
### Instance methods
|
||||
|
||||
The available instance methods are listed below. The specified config will be merged with the instance config.
|
||||
|
||||
##### axios#request(config)
|
||||
##### axios#get(url[, config])
|
||||
##### axios#delete(url[, config])
|
||||
##### axios#head(url[, config])
|
||||
##### axios#post(url[, data[, config]])
|
||||
##### axios#put(url[, data[, config]])
|
||||
##### axios#patch(url[, data[, config]])
|
||||
|
||||
## Request API
|
||||
|
||||
This is the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
|
||||
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
|
||||
|
||||
```js
|
||||
{
|
||||
@@ -186,10 +211,6 @@ This is the available config options for making requests. Only the `url` is requ
|
||||
// If the request takes longer than `timeout`, the request will be aborted.
|
||||
timeout: 1000,
|
||||
|
||||
// `xDomain` indicates whether the request is cross domain.
|
||||
// This option is required to be passed to support cross domain requests on IE 8/9
|
||||
xDomain: false, //default
|
||||
|
||||
// `withCredentials` indicates whether or not cross-site Access-Control requests
|
||||
// should be made using credentials
|
||||
withCredentials: false, // default
|
||||
@@ -273,6 +294,13 @@ var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
|
||||
axios.interceptors.request.eject(myInterceptor);
|
||||
```
|
||||
|
||||
You can add interceptors to a custom instance of axios.
|
||||
|
||||
```js
|
||||
var instance = axios.create();
|
||||
instance.interceptors.request.use(function () {/*...*/});
|
||||
```
|
||||
|
||||
## Handling Errors
|
||||
|
||||
```js
|
||||
|
||||
Vendored
+176
-119
@@ -1,3 +1,4 @@
|
||||
/* axios v0.7.0 | (c) 2015 by Matt Zabriskie */
|
||||
(function webpackUniversalModuleDefinition(root, factory) {
|
||||
if(typeof exports === 'object' && typeof module === 'object')
|
||||
module.exports = factory();
|
||||
@@ -65,23 +66,9 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
var defaults = __webpack_require__(2);
|
||||
var utils = __webpack_require__(3);
|
||||
var dispatchRequest = __webpack_require__(4);
|
||||
var InterceptorManager = __webpack_require__(11);
|
||||
var InterceptorManager = __webpack_require__(12);
|
||||
|
||||
function Axios (defaultConfig) {
|
||||
this.defaultConfig = utils.merge({
|
||||
headers: {},
|
||||
timeout: defaults.timeout,
|
||||
transformRequest: defaults.transformRequest,
|
||||
transformResponse: defaults.transformResponse
|
||||
}, defaultConfig);
|
||||
|
||||
this.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
}
|
||||
|
||||
Axios.prototype.request = function (config) {
|
||||
var axios = module.exports = function (config) {
|
||||
// Allow for axios('example/url'[, config]) a la fetch API
|
||||
if (typeof config === 'string') {
|
||||
config = utils.merge({
|
||||
@@ -89,7 +76,13 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
}, arguments[1]);
|
||||
}
|
||||
|
||||
config = utils.merge(this.defaultConfig, { method: 'get' }, config);
|
||||
config = utils.merge({
|
||||
method: 'get',
|
||||
headers: {},
|
||||
timeout: defaults.timeout,
|
||||
transformRequest: defaults.transformRequest,
|
||||
transformResponse: defaults.transformResponse
|
||||
}, config);
|
||||
|
||||
// Don't allow overriding defaults.withCredentials
|
||||
config.withCredentials = config.withCredentials || defaults.withCredentials;
|
||||
@@ -98,11 +91,11 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
var chain = [dispatchRequest, undefined];
|
||||
var promise = Promise.resolve(config);
|
||||
|
||||
this.interceptors.request.forEach(function (interceptor) {
|
||||
axios.interceptors.request.forEach(function (interceptor) {
|
||||
chain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
this.interceptors.response.forEach(function (interceptor) {
|
||||
axios.interceptors.response.forEach(function (interceptor) {
|
||||
chain.push(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
@@ -113,14 +106,6 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
return promise;
|
||||
};
|
||||
|
||||
var defaultInstance = new Axios();
|
||||
|
||||
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
|
||||
|
||||
axios.create = function (defaultConfig) {
|
||||
return new Axios(defaultConfig);
|
||||
};
|
||||
|
||||
// Expose defaults
|
||||
axios.defaults = defaults;
|
||||
|
||||
@@ -128,48 +113,42 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
axios.all = function (promises) {
|
||||
return Promise.all(promises);
|
||||
};
|
||||
axios.spread = __webpack_require__(12);
|
||||
axios.spread = __webpack_require__(13);
|
||||
|
||||
// Expose interceptors
|
||||
axios.interceptors = defaultInstance.interceptors;
|
||||
axios.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
(function () {
|
||||
function createShortMethods() {
|
||||
utils.forEach(arguments, function (method) {
|
||||
Axios.prototype[method] = function (url, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
axios[method] = function (url, config) {
|
||||
return axios(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
}
|
||||
|
||||
function createShortMethodsWithData() {
|
||||
utils.forEach(arguments, function (method) {
|
||||
Axios.prototype[method] = function (url, data, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
axios[method] = function (url, data, config) {
|
||||
return axios(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
}
|
||||
|
||||
createShortMethods('delete', 'get', 'head');
|
||||
createShortMethodsWithData('post', 'put', 'patch');
|
||||
})();
|
||||
|
||||
// Helpers
|
||||
function bind (fn, thisArg) {
|
||||
return function () {
|
||||
return fn.apply(thisArg, Array.prototype.slice.call(arguments));
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/***/ },
|
||||
@@ -499,7 +478,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
/* 4 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
|
||||
|
||||
/**
|
||||
* Dispatch a request to the server using whichever adapter
|
||||
@@ -513,11 +492,11 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
try {
|
||||
// For browsers use XHR adapter
|
||||
if ((typeof XMLHttpRequest !== 'undefined') || (typeof ActiveXObject !== 'undefined')) {
|
||||
__webpack_require__(5)(resolve, reject, config);
|
||||
__webpack_require__(6)(resolve, reject, config);
|
||||
}
|
||||
// For node use HTTP adapter
|
||||
else if (typeof process !== 'undefined') {
|
||||
__webpack_require__(5)(resolve, reject, config);
|
||||
__webpack_require__(6)(resolve, reject, config);
|
||||
}
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
@@ -525,10 +504,108 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
|
||||
|
||||
/***/ },
|
||||
/* 5 */
|
||||
/***/ function(module, exports) {
|
||||
|
||||
// shim for using process in browser
|
||||
|
||||
var process = module.exports = {};
|
||||
var queue = [];
|
||||
var draining = false;
|
||||
var currentQueue;
|
||||
var queueIndex = -1;
|
||||
|
||||
function cleanUpNextTick() {
|
||||
draining = false;
|
||||
if (currentQueue.length) {
|
||||
queue = currentQueue.concat(queue);
|
||||
} else {
|
||||
queueIndex = -1;
|
||||
}
|
||||
if (queue.length) {
|
||||
drainQueue();
|
||||
}
|
||||
}
|
||||
|
||||
function drainQueue() {
|
||||
if (draining) {
|
||||
return;
|
||||
}
|
||||
var timeout = setTimeout(cleanUpNextTick);
|
||||
draining = true;
|
||||
|
||||
var len = queue.length;
|
||||
while(len) {
|
||||
currentQueue = queue;
|
||||
queue = [];
|
||||
while (++queueIndex < len) {
|
||||
if (currentQueue) {
|
||||
currentQueue[queueIndex].run();
|
||||
}
|
||||
}
|
||||
queueIndex = -1;
|
||||
len = queue.length;
|
||||
}
|
||||
currentQueue = null;
|
||||
draining = false;
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
process.nextTick = function (fun) {
|
||||
var args = new Array(arguments.length - 1);
|
||||
if (arguments.length > 1) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
args[i - 1] = arguments[i];
|
||||
}
|
||||
}
|
||||
queue.push(new Item(fun, args));
|
||||
if (queue.length === 1 && !draining) {
|
||||
setTimeout(drainQueue, 0);
|
||||
}
|
||||
};
|
||||
|
||||
// v8 likes predictible objects
|
||||
function Item(fun, array) {
|
||||
this.fun = fun;
|
||||
this.array = array;
|
||||
}
|
||||
Item.prototype.run = function () {
|
||||
this.fun.apply(null, this.array);
|
||||
};
|
||||
process.title = 'browser';
|
||||
process.browser = true;
|
||||
process.env = {};
|
||||
process.argv = [];
|
||||
process.version = ''; // empty string to avoid regexp issues
|
||||
process.versions = {};
|
||||
|
||||
function noop() {}
|
||||
|
||||
process.on = noop;
|
||||
process.addListener = noop;
|
||||
process.once = noop;
|
||||
process.off = noop;
|
||||
process.removeListener = noop;
|
||||
process.removeAllListeners = noop;
|
||||
process.emit = noop;
|
||||
|
||||
process.binding = function (name) {
|
||||
throw new Error('process.binding is not supported');
|
||||
};
|
||||
|
||||
process.cwd = function () { return '/' };
|
||||
process.chdir = function (dir) {
|
||||
throw new Error('process.chdir is not supported');
|
||||
};
|
||||
process.umask = function() { return 0; };
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 6 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -537,9 +614,9 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
var defaults = __webpack_require__(2);
|
||||
var utils = __webpack_require__(3);
|
||||
var buildUrl = __webpack_require__(6);
|
||||
var parseHeaders = __webpack_require__(7);
|
||||
var transformData = __webpack_require__(8);
|
||||
var buildUrl = __webpack_require__(7);
|
||||
var parseHeaders = __webpack_require__(8);
|
||||
var transformData = __webpack_require__(9);
|
||||
|
||||
module.exports = function xhrAdapter(resolve, reject, config) {
|
||||
// Transform request data
|
||||
@@ -560,30 +637,18 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
delete requestHeaders['Content-Type']; // Let the browser set it
|
||||
}
|
||||
|
||||
var adapter = (XMLHttpRequest || ActiveXObject),
|
||||
loadEvent = 'onreadystatechange',
|
||||
xDomain = false;
|
||||
|
||||
// For IE 8/9 CORS support
|
||||
if(config.xDomain && window.XDomainRequest){
|
||||
adapter = window.XDomainRequest;
|
||||
loadEvent = 'onload';
|
||||
xDomain = true;
|
||||
}
|
||||
|
||||
// Create the request
|
||||
var request = new adapter('Microsoft.XMLHTTP');
|
||||
|
||||
request.open(config.method.toUpperCase(), buildUrl(config.url, config.params, config.paramsSerializer), true);
|
||||
var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
|
||||
request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true);
|
||||
|
||||
// Set the request timeout in MS
|
||||
request.timeout = config.timeout;
|
||||
|
||||
// Listen for ready state
|
||||
request[loadEvent] = function () {
|
||||
if (request && (request.readyState === 4 || xDomain)) {
|
||||
request.onreadystatechange = function () {
|
||||
if (request && request.readyState === 4) {
|
||||
// Prepare the response
|
||||
var responseHeaders = xDomain ? null : parseHeaders(request.getAllResponseHeaders());
|
||||
var responseHeaders = parseHeaders(request.getAllResponseHeaders());
|
||||
var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
|
||||
var response = {
|
||||
data: transformData(
|
||||
@@ -596,8 +661,9 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
headers: responseHeaders,
|
||||
config: config
|
||||
};
|
||||
|
||||
// Resolve or reject the Promise based on the status
|
||||
((request.status >= 200 && request.status < 300) || (request.responseText && xDomain) ?
|
||||
(request.status >= 200 && request.status < 300 ?
|
||||
resolve :
|
||||
reject)(response);
|
||||
|
||||
@@ -610,8 +676,8 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
// 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__(9);
|
||||
var urlIsSameOrigin = __webpack_require__(10);
|
||||
var cookies = __webpack_require__(10);
|
||||
var urlIsSameOrigin = __webpack_require__(11);
|
||||
|
||||
// Add xsrf header
|
||||
var xsrfValue = urlIsSameOrigin(config.url) ?
|
||||
@@ -624,17 +690,16 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
}
|
||||
|
||||
// Add headers to the request
|
||||
if(!xDomain)
|
||||
utils.forEach(requestHeaders, function (val, key) {
|
||||
// Remove Content-Type if data is undefined
|
||||
if (!data && key.toLowerCase() === 'content-type') {
|
||||
delete requestHeaders[key];
|
||||
}
|
||||
// Otherwise add header to the request
|
||||
else {
|
||||
request.setRequestHeader(key, val);
|
||||
}
|
||||
});
|
||||
utils.forEach(requestHeaders, function (val, key) {
|
||||
// Remove Content-Type if data is undefined
|
||||
if (!data && key.toLowerCase() === 'content-type') {
|
||||
delete requestHeaders[key];
|
||||
}
|
||||
// Otherwise add header to the request
|
||||
else {
|
||||
request.setRequestHeader(key, val);
|
||||
}
|
||||
});
|
||||
|
||||
// Add withCredentials to request if needed
|
||||
if (config.withCredentials) {
|
||||
@@ -662,7 +727,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 6 */
|
||||
/* 7 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -687,47 +752,39 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
* @param {object} [params] The params to be appended
|
||||
* @returns {string} The formatted url
|
||||
*/
|
||||
module.exports = function buildUrl(url, params, paramsSerializer) {
|
||||
module.exports = function buildUrl(url, params) {
|
||||
if (!params) {
|
||||
return url;
|
||||
}
|
||||
|
||||
var serializedParams;
|
||||
if (paramsSerializer) {
|
||||
serializedParams = paramsSerializer(params);
|
||||
}
|
||||
else {
|
||||
var parts = [];
|
||||
var parts = [];
|
||||
|
||||
utils.forEach(params, function (val, key) {
|
||||
if (val === null || typeof val === 'undefined') {
|
||||
return;
|
||||
utils.forEach(params, function (val, key) {
|
||||
if (val === null || typeof val === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (utils.isArray(val)) {
|
||||
key = key + '[]';
|
||||
}
|
||||
|
||||
if (!utils.isArray(val)) {
|
||||
val = [val];
|
||||
}
|
||||
|
||||
utils.forEach(val, function (v) {
|
||||
if (utils.isDate(v)) {
|
||||
v = v.toISOString();
|
||||
}
|
||||
|
||||
if (utils.isArray(val)) {
|
||||
key = key + '[]';
|
||||
else if (utils.isObject(v)) {
|
||||
v = JSON.stringify(v);
|
||||
}
|
||||
|
||||
if (!utils.isArray(val)) {
|
||||
val = [val];
|
||||
}
|
||||
|
||||
utils.forEach(val, function (v) {
|
||||
if (utils.isDate(v)) {
|
||||
v = v.toISOString();
|
||||
}
|
||||
else if (utils.isObject(v)) {
|
||||
v = JSON.stringify(v);
|
||||
}
|
||||
parts.push(encode(key) + '=' + encode(v));
|
||||
});
|
||||
parts.push(encode(key) + '=' + encode(v));
|
||||
});
|
||||
});
|
||||
|
||||
serializedParams = parts.join('&');
|
||||
}
|
||||
|
||||
if (serializedParams) {
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
||||
if (parts.length > 0) {
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&');
|
||||
}
|
||||
|
||||
return url;
|
||||
@@ -735,7 +792,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 7 */
|
||||
/* 8 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -775,7 +832,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 8 */
|
||||
/* 9 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -800,7 +857,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 9 */
|
||||
/* 10 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -849,7 +906,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 10 */
|
||||
/* 11 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -913,7 +970,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 11 */
|
||||
/* 12 */
|
||||
/***/ function(module, exports, __webpack_require__) {
|
||||
|
||||
'use strict';
|
||||
@@ -971,7 +1028,7 @@ return /******/ (function(modules) { // webpackBootstrap
|
||||
|
||||
|
||||
/***/ },
|
||||
/* 12 */
|
||||
/* 13 */
|
||||
/***/ function(module, exports) {
|
||||
|
||||
'use strict';
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+22
-6
@@ -2,11 +2,12 @@
|
||||
|
||||
var defaults = require('./../defaults');
|
||||
var utils = require('./../utils');
|
||||
var buildUrl = require('./../helpers/buildUrl');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var transformData = require('./../helpers/transformData');
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
var http = require('follow-redirects').http;
|
||||
var https = require('follow-redirects').https;
|
||||
var url = require('url');
|
||||
var zlib = require('zlib');
|
||||
var pkg = require('./../../package.json');
|
||||
var Buffer = require('buffer').Buffer;
|
||||
|
||||
@@ -50,7 +51,7 @@ module.exports = function httpAdapter(resolve, reject, config) {
|
||||
var options = {
|
||||
host: parsed.hostname,
|
||||
port: parsed.port,
|
||||
path: buildUrl(parsed.path, config.params).replace(/^\?/, ''),
|
||||
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
||||
method: config.method,
|
||||
headers: headers,
|
||||
agent: config.agent
|
||||
@@ -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');
|
||||
|
||||
+8
-8
@@ -4,9 +4,10 @@
|
||||
|
||||
var defaults = require('./../defaults');
|
||||
var utils = require('./../utils');
|
||||
var buildUrl = require('./../helpers/buildUrl');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var parseHeaders = require('./../helpers/parseHeaders');
|
||||
var transformData = require('./../helpers/transformData');
|
||||
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
||||
|
||||
module.exports = function xhrAdapter(resolve, reject, config) {
|
||||
// Transform request data
|
||||
@@ -27,12 +28,12 @@ module.exports = function xhrAdapter(resolve, reject, config) {
|
||||
delete requestHeaders['Content-Type']; // Let the browser set it
|
||||
}
|
||||
|
||||
var adapter = (XMLHttpRequest || ActiveXObject),
|
||||
loadEvent = 'onreadystatechange',
|
||||
xDomain = false;
|
||||
var adapter = (XMLHttpRequest || ActiveXObject);
|
||||
var loadEvent = 'onreadystatechange';
|
||||
var xDomain = false;
|
||||
|
||||
// For IE 8/9 CORS support
|
||||
if(config.xDomain && window.XDomainRequest){
|
||||
if(!isURLSameOrigin(config.url) && window.XDomainRequest){
|
||||
adapter = window.XDomainRequest;
|
||||
loadEvent = 'onload';
|
||||
xDomain = true;
|
||||
@@ -40,7 +41,6 @@ module.exports = function xhrAdapter(resolve, reject, config) {
|
||||
|
||||
// Create the request
|
||||
var request = new adapter('Microsoft.XMLHTTP');
|
||||
|
||||
request.open(config.method.toUpperCase(), buildUrl(config.url, config.params, config.paramsSerializer), true);
|
||||
|
||||
// Set the request timeout in MS
|
||||
@@ -78,10 +78,10 @@ module.exports = function xhrAdapter(resolve, reject, config) {
|
||||
// Specifically not if we're in a web worker, or react-native.
|
||||
if (utils.isStandardBrowserEnv()) {
|
||||
var cookies = require('./../helpers/cookies');
|
||||
var urlIsSameOrigin = require('./../helpers/urlIsSameOrigin');
|
||||
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
||||
|
||||
// Add xsrf header
|
||||
var xsrfValue = urlIsSameOrigin(config.url) ?
|
||||
var xsrfValue = isURLSameOrigin(config.url) ?
|
||||
cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) :
|
||||
undefined;
|
||||
|
||||
|
||||
+27
-32
@@ -71,40 +71,35 @@ axios.spread = require('./helpers/spread');
|
||||
// Expose interceptors
|
||||
axios.interceptors = defaultInstance.interceptors;
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
(function () {
|
||||
function createShortMethods() {
|
||||
utils.forEach(arguments, function (method) {
|
||||
Axios.prototype[method] = function (url, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
}
|
||||
|
||||
function createShortMethodsWithData() {
|
||||
utils.forEach(arguments, function (method) {
|
||||
Axios.prototype[method] = function (url, data, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
}
|
||||
|
||||
createShortMethods('delete', 'get', 'head');
|
||||
createShortMethodsWithData('post', 'put', 'patch');
|
||||
})();
|
||||
|
||||
// Helpers
|
||||
function bind (fn, thisArg) {
|
||||
return function () {
|
||||
return fn.apply(thisArg, Array.prototype.slice.call(arguments));
|
||||
var args = new Array(arguments.length);
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
return fn.apply(thisArg, args);
|
||||
};
|
||||
}
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
utils.forEach(['delete', 'get', 'head'], function (method) {
|
||||
Axios.prototype[method] = function (url, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
|
||||
utils.forEach(['post', 'put', 'patch'], function (method) {
|
||||
Axios.prototype[method] = function (url, data, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
axios[method] = bind(Axios.prototype[method], defaultInstance);
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ function encode(val) {
|
||||
* @param {object} [params] The params to be appended
|
||||
* @returns {string} The formatted url
|
||||
*/
|
||||
module.exports = function buildUrl(url, params, paramsSerializer) {
|
||||
module.exports = function buildURL(url, params, paramsSerializer) {
|
||||
if (!params) {
|
||||
return url;
|
||||
}
|
||||
|
||||
+42
-32
@@ -1,43 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* WARNING:
|
||||
* This file makes references to objects that aren't safe in all environments.
|
||||
* Please see lib/utils.isStandardBrowserEnv before including this file.
|
||||
*/
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = {
|
||||
write: function write(name, value, expires, path, domain, secure) {
|
||||
var cookie = [];
|
||||
cookie.push(name + '=' + encodeURIComponent(value));
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
if (utils.isNumber(expires)) {
|
||||
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||
}
|
||||
// Standard browser envs support document.cookie
|
||||
(function () {
|
||||
return {
|
||||
write: function write(name, value, expires, path, domain, secure) {
|
||||
var cookie = [];
|
||||
cookie.push(name + '=' + encodeURIComponent(value));
|
||||
|
||||
if (utils.isString(path)) {
|
||||
cookie.push('path=' + path);
|
||||
}
|
||||
if (utils.isNumber(expires)) {
|
||||
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||
}
|
||||
|
||||
if (utils.isString(domain)) {
|
||||
cookie.push('domain=' + domain);
|
||||
}
|
||||
if (utils.isString(path)) {
|
||||
cookie.push('path=' + path);
|
||||
}
|
||||
|
||||
if (secure === true) {
|
||||
cookie.push('secure');
|
||||
}
|
||||
if (utils.isString(domain)) {
|
||||
cookie.push('domain=' + domain);
|
||||
}
|
||||
|
||||
document.cookie = cookie.join('; ');
|
||||
},
|
||||
if (secure === true) {
|
||||
cookie.push('secure');
|
||||
}
|
||||
|
||||
read: function read(name) {
|
||||
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||
return (match ? decodeURIComponent(match[3]) : null);
|
||||
},
|
||||
document.cookie = cookie.join('; ');
|
||||
},
|
||||
|
||||
remove: function remove(name) {
|
||||
this.write(name, '', Date.now() - 86400000);
|
||||
}
|
||||
};
|
||||
read: function read(name) {
|
||||
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||
return (match ? decodeURIComponent(match[3]) : null);
|
||||
},
|
||||
|
||||
remove: function remove(name) {
|
||||
this.write(name, '', Date.now() - 86400000);
|
||||
}
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser env (web workers, react-native) lack needed support.
|
||||
(function () {
|
||||
return {
|
||||
write: function write() {},
|
||||
read: function read() { return null; },
|
||||
remove: function remove() {}
|
||||
};
|
||||
})()
|
||||
);
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
// Standard browser envs have full support of the APIs needed to test
|
||||
// whether the request URL is of the same origin as current location.
|
||||
(function () {
|
||||
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
||||
var urlParsingNode = document.createElement('a');
|
||||
var originURL;
|
||||
|
||||
/**
|
||||
* Parse a URL to discover it's components
|
||||
*
|
||||
* @param {String} url The URL to be parsed
|
||||
* @returns {Object}
|
||||
*/
|
||||
function resolveURL(url) {
|
||||
var href = url;
|
||||
|
||||
if (msie) {
|
||||
// IE needs attribute set twice to normalize properties
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
href = urlParsingNode.href;
|
||||
}
|
||||
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
|
||||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
||||
return {
|
||||
href: urlParsingNode.href,
|
||||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
||||
host: urlParsingNode.host,
|
||||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
||||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
||||
hostname: urlParsingNode.hostname,
|
||||
port: urlParsingNode.port,
|
||||
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
||||
urlParsingNode.pathname :
|
||||
'/' + urlParsingNode.pathname
|
||||
};
|
||||
}
|
||||
|
||||
originURL = resolveURL(window.location.href);
|
||||
|
||||
/**
|
||||
* Determine if a URL shares the same origin as the current location
|
||||
*
|
||||
* @param {String} requestURL The URL to test
|
||||
* @returns {boolean} True if URL shares the same origin, otherwise false
|
||||
*/
|
||||
return function isURLSameOrigin(requestURL) {
|
||||
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
|
||||
return (parsed.protocol === originURL.protocol &&
|
||||
parsed.host === originURL.host);
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser envs (web workers, react-native) lack needed support.
|
||||
(function () {
|
||||
return function isURLSameOrigin() {
|
||||
return true;
|
||||
};
|
||||
})()
|
||||
);
|
||||
@@ -1,58 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* WARNING:
|
||||
* This file makes references to objects that aren't safe in all environments.
|
||||
* Please see lib/utils.isStandardBrowserEnv before including this file.
|
||||
*/
|
||||
|
||||
var utils = require('./../utils');
|
||||
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
||||
var urlParsingNode = document.createElement('a');
|
||||
var originUrl;
|
||||
|
||||
/**
|
||||
* Parse a URL to discover it's components
|
||||
*
|
||||
* @param {String} url The URL to be parsed
|
||||
* @returns {Object}
|
||||
*/
|
||||
function urlResolve(url) {
|
||||
var href = url;
|
||||
|
||||
if (msie) {
|
||||
// IE needs attribute set twice to normalize properties
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
href = urlParsingNode.href;
|
||||
}
|
||||
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
|
||||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
||||
return {
|
||||
href: urlParsingNode.href,
|
||||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
||||
host: urlParsingNode.host,
|
||||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
||||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
||||
hostname: urlParsingNode.hostname,
|
||||
port: urlParsingNode.port,
|
||||
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
||||
urlParsingNode.pathname :
|
||||
'/' + urlParsingNode.pathname
|
||||
};
|
||||
}
|
||||
|
||||
originUrl = urlResolve(window.location.href);
|
||||
|
||||
/**
|
||||
* Determine if a URL shares the same origin as the current location
|
||||
*
|
||||
* @param {String} requestUrl The URL to test
|
||||
* @returns {boolean} True if URL shares the same origin, otherwise false
|
||||
*/
|
||||
module.exports = function urlIsSameOrigin(requestUrl) {
|
||||
var parsed = (utils.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
|
||||
return (parsed.protocol === originUrl.protocol &&
|
||||
parsed.host === originUrl.host);
|
||||
};
|
||||
+9
-22
@@ -130,16 +130,6 @@ function trim(str) {
|
||||
return str.replace(/^\s*/, '').replace(/\s*$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is an Arguments object
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is an Arguments object, otherwise false
|
||||
*/
|
||||
function isArguments(val) {
|
||||
return toString.call(val) === '[object Arguments]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if we're running in a standard browser environment
|
||||
*
|
||||
@@ -151,7 +141,7 @@ function isArguments(val) {
|
||||
* typeof document -> undefined
|
||||
*
|
||||
* react-native:
|
||||
* typeof document.createelement -> undefined
|
||||
* typeof document.createElement -> undefined
|
||||
*/
|
||||
function isStandardBrowserEnv() {
|
||||
return (
|
||||
@@ -164,7 +154,7 @@ function isStandardBrowserEnv() {
|
||||
/**
|
||||
* Iterate over an Array or an Object invoking a function for each item.
|
||||
*
|
||||
* If `obj` is an Array or arguments callback will be called passing
|
||||
* If `obj` is an Array callback will be called passing
|
||||
* the value, index, and complete array for each item.
|
||||
*
|
||||
* If 'obj' is an Object callback will be called passing
|
||||
@@ -179,16 +169,13 @@ function forEach(obj, fn) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if obj is array-like
|
||||
var isArrayLike = isArray(obj) || isArguments(obj);
|
||||
|
||||
// Force an array if not already something iterable
|
||||
if (typeof obj !== 'object' && !isArrayLike) {
|
||||
if (typeof obj !== 'object' && !isArray(obj)) {
|
||||
obj = [obj];
|
||||
}
|
||||
|
||||
// Iterate over array values
|
||||
if (isArrayLike) {
|
||||
if (isArray(obj)) {
|
||||
for (var i = 0, l = obj.length; i < l; i++) {
|
||||
fn.call(null, obj[i], i, obj);
|
||||
}
|
||||
@@ -222,11 +209,11 @@ function forEach(obj, fn) {
|
||||
*/
|
||||
function merge(/*obj1, obj2, obj3, ...*/) {
|
||||
var result = {};
|
||||
forEach(arguments, function (obj) {
|
||||
forEach(obj, function (val, key) {
|
||||
result[key] = val;
|
||||
});
|
||||
});
|
||||
var assignValue = function (val, key) { result[key] = val; };
|
||||
var length = arguments.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
forEach(arguments[i], assignValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,5 +62,8 @@
|
||||
},
|
||||
"typescript": {
|
||||
"definition": "./axios.d.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"follow-redirects": "0.0.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
var buildUrl = require('../../../lib/helpers/buildUrl');
|
||||
var buildURL = require('../../../lib/helpers/buildURL');
|
||||
|
||||
describe('helpers::buildUrl', function () {
|
||||
describe('helpers::buildURL', function () {
|
||||
it('should support null params', function () {
|
||||
expect(buildUrl('/foo')).toEqual('/foo');
|
||||
expect(buildURL('/foo')).toEqual('/foo');
|
||||
});
|
||||
|
||||
it('should support params', function () {
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
foo: 'bar'
|
||||
})).toEqual('/foo?foo=bar');
|
||||
});
|
||||
|
||||
it('should support object params', function () {
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
foo: {
|
||||
bar: 'baz'
|
||||
}
|
||||
@@ -22,31 +22,31 @@ describe('helpers::buildUrl', function () {
|
||||
it('should support date params', function () {
|
||||
var date = new Date();
|
||||
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
date: date
|
||||
})).toEqual('/foo?date=' + date.toISOString());
|
||||
});
|
||||
|
||||
it('should support array params', function () {
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
foo: ['bar', 'baz']
|
||||
})).toEqual('/foo?foo[]=bar&foo[]=baz');
|
||||
});
|
||||
|
||||
it('should support special char params', function () {
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
foo: '@:$, '
|
||||
})).toEqual('/foo?foo=@:$,+');
|
||||
});
|
||||
|
||||
it('should support existing params', function () {
|
||||
expect(buildUrl('/foo?foo=bar', {
|
||||
expect(buildURL('/foo?foo=bar', {
|
||||
bar: 'baz'
|
||||
})).toEqual('/foo?foo=bar&bar=baz');
|
||||
});
|
||||
|
||||
it('should support "length" parameter', function () {
|
||||
expect(buildUrl('/foo', {
|
||||
expect(buildURL('/foo', {
|
||||
query: 'bar',
|
||||
start: 0,
|
||||
length: 5
|
||||
@@ -57,7 +57,7 @@ describe('helpers::buildUrl', function () {
|
||||
serializer = sinon.stub();
|
||||
params = {foo: 'bar'};
|
||||
serializer.returns('foo=bar');
|
||||
expect(buildUrl('/foo', params, serializer)).toEqual('/foo?foo=bar');
|
||||
expect(buildURL('/foo', params, serializer)).toEqual('/foo?foo=bar');
|
||||
expect(serializer.calledOnce).toBe(true);
|
||||
expect(serializer.calledWith(params)).toBe(true);
|
||||
})
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
var isURLSameOrigin = require('../../../lib/helpers/isURLSameOrigin');
|
||||
|
||||
describe('helpers::isURLSameOrigin', function () {
|
||||
it('should detect same origin', function () {
|
||||
expect(isURLSameOrigin(window.location.href)).toEqual(true);
|
||||
});
|
||||
|
||||
it('should detect different origin', function () {
|
||||
expect(isURLSameOrigin('https://github.com/mzabriskie/axios')).toEqual(false);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +0,0 @@
|
||||
var urlIsSameOrigin = require('../../../lib/helpers/urlIsSameOrigin');
|
||||
|
||||
describe('helpers::urlIsSameOrigin', function () {
|
||||
it('should detect same origin', function () {
|
||||
expect(urlIsSameOrigin(window.location.href)).toEqual(true);
|
||||
});
|
||||
|
||||
it('should detect different origin', function () {
|
||||
expect(urlIsSameOrigin('https://github.com/mzabriskie/axios')).toEqual(false);
|
||||
});
|
||||
});
|
||||
@@ -11,18 +11,6 @@ describe('utils::forEach', function () {
|
||||
expect(sum).toEqual(15);
|
||||
});
|
||||
|
||||
it('should loop over arguments', function () {
|
||||
var sum = 0;
|
||||
|
||||
(function () {
|
||||
forEach(arguments, function (val) {
|
||||
sum += val;
|
||||
});
|
||||
})(1, 2, 3, 4, 5);
|
||||
|
||||
expect(sum).toEqual(15);
|
||||
});
|
||||
|
||||
it('should loop over object keys', function () {
|
||||
var keys = '';
|
||||
var vals = 0;
|
||||
@@ -61,4 +49,3 @@ describe('utils::forEach', function () {
|
||||
expect(count).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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('ж');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user