提交 e5e14daa 编写于 作者: V Vineet Hawal

Merge branch 'master' of github.com:mzabriskie/axios into xDomainRequestSupport

Conflicts:
	lib/adapters/xhr.js
......@@ -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
......
/* 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)) {
key = key + '[]';
}
if (!utils.isArray(val)) {
val = [val];
}
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));
});
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));
});
});
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';
......
此差异已折叠。
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){e.exports=r(1)},function(e,t,r){"use strict";function n(e){this.defaultConfig=s.merge({headers:{},timeout:i.timeout,transformRequest:i.transformRequest,transformResponse:i.transformResponse},e),this.interceptors={request:new a,response:new a}}function o(e,t){return function(){return e.apply(t,Array.prototype.slice.call(arguments))}}var i=r(2),s=r(3),u=r(4),a=r(11);n.prototype.request=function(e){"string"==typeof e&&(e=s.merge({url:arguments[0]},arguments[1])),e=s.merge(this.defaultConfig,{method:"get"},e),e.withCredentials=e.withCredentials||i.withCredentials;var t=[u,void 0],r=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)r=r.then(t.shift(),t.shift());return r};var f=new n,c=e.exports=o(n.prototype.request,f);c.create=function(e){return new n(e)},c.defaults=i,c.all=function(e){return Promise.all(e)},c.spread=r(12),c.interceptors=f.interceptors,function(){function e(){s.forEach(arguments,function(e){n.prototype[e]=function(t,r){return this.request(s.merge(r||{},{method:e,url:t}))},c[e]=o(n.prototype[e],f)})}function t(){s.forEach(arguments,function(e){n.prototype[e]=function(t,r,n){return this.request(s.merge(n||{},{method:e,url:t,data:r}))},c[e]=o(n.prototype[e],f)})}e("delete","get","head"),t("post","put","patch")}()},function(e,t,r){"use strict";var n=r(3),o=/^\)\]\}',?\n/,i={"Content-Type":"application/x-www-form-urlencoded"};e.exports={transformRequest:[function(e,t){return n.isFormData(e)?e:n.isArrayBuffer(e)?e:n.isArrayBufferView(e)?e.buffer:!n.isObject(e)||n.isFile(e)||n.isBlob(e)?e:(n.isUndefined(t)||(n.forEach(t,function(e,r){"content-type"===r.toLowerCase()&&(t["Content-Type"]=e)}),n.isUndefined(t["Content-Type"])&&(t["Content-Type"]="application/json;charset=utf-8")),JSON.stringify(e))}],transformResponse:[function(e){if("string"==typeof e){e=e.replace(o,"");try{e=JSON.parse(e)}catch(t){}}return e}],headers:{common:{Accept:"application/json, text/plain, */*"},patch:n.merge(i),post:n.merge(i),put:n.merge(i)},timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"}},function(e,t){"use strict";function r(e){return"[object Array]"===x.call(e)}function n(e){return"[object ArrayBuffer]"===x.call(e)}function o(e){return"[object FormData]"===x.call(e)}function i(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function s(e){return"string"==typeof e}function u(e){return"number"==typeof e}function a(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function c(e){return"[object Date]"===x.call(e)}function p(e){return"[object File]"===x.call(e)}function l(e){return"[object Blob]"===x.call(e)}function d(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function h(e){return"[object Arguments]"===x.call(e)}function m(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"function"==typeof document.createElement}function y(e,t){if(null!==e&&"undefined"!=typeof e){var n=r(e)||h(e);if("object"==typeof e||n||(e=[e]),n)for(var o=0,i=e.length;i>o;o++)t.call(null,e[o],o,e);else for(var s in e)e.hasOwnProperty(s)&&t.call(null,e[s],s,e)}}function g(){var e={};return y(arguments,function(t){y(t,function(t,r){e[r]=t})}),e}var x=Object.prototype.toString;e.exports={isArray:r,isArrayBuffer:n,isFormData:o,isArrayBufferView:i,isString:s,isNumber:u,isObject:f,isUndefined:a,isDate:c,isFile:p,isBlob:l,isStandardBrowserEnv:m,forEach:y,merge:g,trim:d}},function(e,t,r){"use strict";e.exports=function(e){return new Promise(function(t,n){try{"undefined"!=typeof XMLHttpRequest||"undefined"!=typeof ActiveXObject?r(5)(t,n,e):"undefined"!=typeof process&&r(5)(t,n,e)}catch(o){n(o)}})}},function(e,t,r){"use strict";var n=r(2),o=r(3),i=r(6),s=r(7),u=r(8);e.exports=function(e,t,a){var f=u(a.data,a.headers,a.transformRequest),c=o.merge(n.headers.common,n.headers[a.method]||{},a.headers||{});o.isFormData(f)&&delete c["Content-Type"];var p=XMLHttpRequest||ActiveXObject,l="onreadystatechange",d=!1;a.xDomain&&window.XDomainRequest&&(p=window.XDomainRequest,l="onload",d=!0);var h=new p("Microsoft.XMLHTTP");if(h.open(a.method.toUpperCase(),i(a.url,a.params,a.paramsSerializer),!0),h.timeout=a.timeout,h[l]=function(){if(h&&(4===h.readyState||d)){var r=d?null:s(h.getAllResponseHeaders()),n=-1!==["text",""].indexOf(a.responseType||"")?h.responseText:h.response,o={data:u(n,r,a.transformResponse),status:h.status,statusText:h.statusText,headers:r,config:a};(h.status>=200&&h.status<300||h.responseText&&d?e:t)(o),h=null}},o.isStandardBrowserEnv()){var m=r(9),y=r(10),g=y(a.url)?m.read(a.xsrfCookieName||n.xsrfCookieName):void 0;g&&(c[a.xsrfHeaderName||n.xsrfHeaderName]=g)}if(d||o.forEach(c,function(e,t){f||"content-type"!==t.toLowerCase()?h.setRequestHeader(t,e):delete c[t]}),a.withCredentials&&(h.withCredentials=!0),a.responseType)try{h.responseType=a.responseType}catch(x){if("json"!==h.responseType)throw x}o.isArrayBuffer(f)&&(f=new DataView(f)),h.send(f)}},function(e,t,r){"use strict";function n(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=r(3);e.exports=function(e,t,r){if(!t)return e;var i;if(r)i=r(t);else{var s=[];o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)&&(t+="[]"),o.isArray(e)||(e=[e]),o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),s.push(n(t)+"="+n(e))}))}),i=s.join("&")}return i&&(e+=(-1===e.indexOf("?")?"?":"&")+i),e}},function(e,t,r){"use strict";var n=r(3);e.exports=function(e){var t,r,o,i={};return e?(n.forEach(e.split("\n"),function(e){o=e.indexOf(":"),t=n.trim(e.substr(0,o)).toLowerCase(),r=n.trim(e.substr(o+1)),t&&(i[t]=i[t]?i[t]+", "+r:r)}),i):i}},function(e,t,r){"use strict";var n=r(3);e.exports=function(e,t,r){return n.forEach(r,function(r){e=r(e,t)}),e}},function(e,t,r){"use strict";var n=r(3);e.exports={write:function(e,t,r,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),n.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),n.isString(o)&&u.push("path="+o),n.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}},function(e,t,r){"use strict";function n(e){var t=e;return s&&(u.setAttribute("href",t),t=u.href),u.setAttribute("href",t),{href:u.href,protocol:u.protocol?u.protocol.replace(/:$/,""):"",host:u.host,search:u.search?u.search.replace(/^\?/,""):"",hash:u.hash?u.hash.replace(/^#/,""):"",hostname:u.hostname,port:u.port,pathname:"/"===u.pathname.charAt(0)?u.pathname:"/"+u.pathname}}var o,i=r(3),s=/(msie|trident)/i.test(navigator.userAgent),u=document.createElement("a");o=n(window.location.href),e.exports=function(e){var t=i.isString(e)?n(e):e;return t.protocol===o.protocol&&t.host===o.host}},function(e,t,r){"use strict";function n(){this.handlers=[]}var o=r(3);n.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},n.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},n.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=n},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});
/* axios v0.7.0 | (c) 2015 by Matt Zabriskie */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";var r=n(2),o=n(3),i=n(4),s=n(12),u=e.exports=function(e){"string"==typeof e&&(e=o.merge({url:arguments[0]},arguments[1])),e=o.merge({method:"get",headers:{},timeout:r.timeout,transformRequest:r.transformRequest,transformResponse:r.transformResponse},e),e.withCredentials=e.withCredentials||r.withCredentials;var t=[i,void 0],n=Promise.resolve(e);for(u.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),u.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n};u.defaults=r,u.all=function(e){return Promise.all(e)},u.spread=n(13),u.interceptors={request:new s,response:new s},function(){function e(){o.forEach(arguments,function(e){u[e]=function(t,n){return u(o.merge(n||{},{method:e,url:t}))}})}function t(){o.forEach(arguments,function(e){u[e]=function(t,n,r){return u(o.merge(r||{},{method:e,url:t,data:n}))}})}e("delete","get","head"),t("post","put","patch")}()},function(e,t,n){"use strict";var r=n(3),o=/^\)\]\}',?\n/,i={"Content-Type":"application/x-www-form-urlencoded"};e.exports={transformRequest:[function(e,t){return r.isFormData(e)?e:r.isArrayBuffer(e)?e:r.isArrayBufferView(e)?e.buffer:!r.isObject(e)||r.isFile(e)||r.isBlob(e)?e:(r.isUndefined(t)||(r.forEach(t,function(e,n){"content-type"===n.toLowerCase()&&(t["Content-Type"]=e)}),r.isUndefined(t["Content-Type"])&&(t["Content-Type"]="application/json;charset=utf-8")),JSON.stringify(e))}],transformResponse:[function(e){if("string"==typeof e){e=e.replace(o,"");try{e=JSON.parse(e)}catch(t){}}return e}],headers:{common:{Accept:"application/json, text/plain, */*"},patch:r.merge(i),post:r.merge(i),put:r.merge(i)},timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"}},function(e,t){"use strict";function n(e){return"[object Array]"===v.call(e)}function r(e){return"[object ArrayBuffer]"===v.call(e)}function o(e){return"[object FormData]"===v.call(e)}function i(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function s(e){return"string"==typeof e}function u(e){return"number"==typeof e}function a(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function c(e){return"[object Date]"===v.call(e)}function p(e){return"[object File]"===v.call(e)}function l(e){return"[object Blob]"===v.call(e)}function d(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function h(e){return"[object Arguments]"===v.call(e)}function m(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"function"==typeof document.createElement}function y(e,t){if(null!==e&&"undefined"!=typeof e){var r=n(e)||h(e);if("object"==typeof e||r||(e=[e]),r)for(var o=0,i=e.length;i>o;o++)t.call(null,e[o],o,e);else for(var s in e)e.hasOwnProperty(s)&&t.call(null,e[s],s,e)}}function g(){var e={};return y(arguments,function(t){y(t,function(t,n){e[n]=t})}),e}var v=Object.prototype.toString;e.exports={isArray:n,isArrayBuffer:r,isFormData:o,isArrayBufferView:i,isString:s,isNumber:u,isObject:f,isUndefined:a,isDate:c,isFile:p,isBlob:l,isStandardBrowserEnv:m,forEach:y,merge:g,trim:d}},function(e,t,n){(function(t){"use strict";e.exports=function(e){return new Promise(function(r,o){try{"undefined"!=typeof XMLHttpRequest||"undefined"!=typeof ActiveXObject?n(6)(r,o,e):"undefined"!=typeof t&&n(6)(r,o,e)}catch(i){o(i)}})}}).call(t,n(5))},function(e,t){function n(){f=!1,s.length?a=s.concat(a):c=-1,a.length&&r()}function r(){if(!f){var e=setTimeout(n);f=!0;for(var t=a.length;t;){for(s=a,a=[];++c<t;)s&&s[c].run();c=-1,t=a.length}s=null,f=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function i(){}var s,u=e.exports={},a=[],f=!1,c=-1;u.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];a.push(new o(e,t)),1!==a.length||f||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=i,u.addListener=i,u.once=i,u.off=i,u.removeListener=i,u.removeAllListeners=i,u.emit=i,u.binding=function(e){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(e){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},function(e,t,n){"use strict";var r=n(2),o=n(3),i=n(7),s=n(8),u=n(9);e.exports=function(e,t,a){var f=u(a.data,a.headers,a.transformRequest),c=o.merge(r.headers.common,r.headers[a.method]||{},a.headers||{});o.isFormData(f)&&delete c["Content-Type"];var p=new(XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");if(p.open(a.method.toUpperCase(),i(a.url,a.params),!0),p.timeout=a.timeout,p.onreadystatechange=function(){if(p&&4===p.readyState){var n=s(p.getAllResponseHeaders()),r=-1!==["text",""].indexOf(a.responseType||"")?p.responseText:p.response,o={data:u(r,n,a.transformResponse),status:p.status,statusText:p.statusText,headers:n,config:a};(p.status>=200&&p.status<300?e:t)(o),p=null}},o.isStandardBrowserEnv()){var l=n(10),d=n(11),h=d(a.url)?l.read(a.xsrfCookieName||r.xsrfCookieName):void 0;h&&(c[a.xsrfHeaderName||r.xsrfHeaderName]=h)}if(o.forEach(c,function(e,t){f||"content-type"!==t.toLowerCase()?p.setRequestHeader(t,e):delete c[t]}),a.withCredentials&&(p.withCredentials=!0),a.responseType)try{p.responseType=a.responseType}catch(m){if("json"!==p.responseType)throw m}o.isArrayBuffer(f)&&(f=new DataView(f)),p.send(f)}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(3);e.exports=function(e,t){if(!t)return e;var n=[];return o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)&&(t+="[]"),o.isArray(e)||(e=[e]),o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),n.push(r(t)+"="+r(e))}))}),n.length>0&&(e+=(-1===e.indexOf("?")?"?":"&")+n.join("&")),e}},function(e,t,n){"use strict";var r=n(3);e.exports=function(e){var t,n,o,i={};return e?(r.forEach(e.split("\n"),function(e){o=e.indexOf(":"),t=r.trim(e.substr(0,o)).toLowerCase(),n=r.trim(e.substr(o+1)),t&&(i[t]=i[t]?i[t]+", "+n:n)}),i):i}},function(e,t,n){"use strict";var r=n(3);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t,n){"use strict";var r=n(3);e.exports={write:function(e,t,n,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}},function(e,t,n){"use strict";function r(e){var t=e;return s&&(u.setAttribute("href",t),t=u.href),u.setAttribute("href",t),{href:u.href,protocol:u.protocol?u.protocol.replace(/:$/,""):"",host:u.host,search:u.search?u.search.replace(/^\?/,""):"",hash:u.hash?u.hash.replace(/^#/,""):"",hostname:u.hostname,port:u.port,pathname:"/"===u.pathname.charAt(0)?u.pathname:"/"+u.pathname}}var o,i=n(3),s=/(msie|trident)/i.test(navigator.userAgent),u=document.createElement("a");o=r(window.location.href),e.exports=function(e){var t=i.isString(e)?r(e):e;return t.protocol===o.protocol&&t.host===o.host}},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(3);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});
//# sourceMappingURL=axios.min.map
\ No newline at end of file
此差异已折叠。
......@@ -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');
......
......@@ -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;
......
......@@ -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;
}
......
'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));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
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);
}
};
module.exports = (
utils.isStandardBrowserEnv() ?
// 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.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
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() {}
};
})()
);
'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;
};
})()
);
'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);
};
......@@ -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"
}
}
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);
})
......
var urlIsSameOrigin = require('../../../lib/helpers/urlIsSameOrigin');
var isURLSameOrigin = require('../../../lib/helpers/isURLSameOrigin');
describe('helpers::urlIsSameOrigin', function () {
describe('helpers::isURLSameOrigin', function () {
it('should detect same origin', function () {
expect(urlIsSameOrigin(window.location.href)).toEqual(true);
expect(isURLSameOrigin(window.location.href)).toEqual(true);
});
it('should detect different origin', function () {
expect(urlIsSameOrigin('https://github.com/mzabriskie/axios')).toEqual(false);
expect(isURLSameOrigin('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);
});
});
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('ж');
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册