为了方便使用,axios对象既能作对象使用,又能作函数使用.node
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
这一点axios是如何作到的,能够看到instance实际上是一个绑定this的函数,调用axios就是调用context.requestios
function createInstance(){ // 能当作函数使用的秘密 var instance = bind(Axios.prototype.request, context); // 能当作对象使用的秘密 utils.extend(instance, Axios.prototype, context); // 要拿到构造函数继承的属性 utils.extend(instance, context); return instance } var axios = createInstance(defaults);
接下来咱们看一下request方法,全部http请求的发送都会调用Axios.prototype.request
,这个函数能够认为是整个axios的骨架,很是重要。axios
Axios.prototype.request = function request(config) { // 每一个请求都会从新合成一个config,因此经过操做config对象,你能够标识请求,作某些操做,事实上每一个axios的拦截器都能拿到config对象 config = utils.merge(defaults, this.defaults, { method: 'get' }, config); // 挂载拦截器的主要逻辑 var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }
从拦截器中的主要逻辑,咱们能够获得如下几点:promise
interceptors.request.use(function () {/*...*/})
执行的顺序有关,即先use
的请求拦截器会先执行。看一下,不一样的http method是怎么复用request方法的缓存
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; });
接下来咱们看dispatchRequest的核心逻辑:异步
// 处理config... var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); });
能够看到dispatchRequest的核心逻辑大概有三步async
因此经过dispatchRequest方法的阅读,咱们能够获得如下启示:函数
至此,咱们已经把axios的核心逻辑阅读完毕,从中咱们也能够看到axios的易用性和可拓展性很是强。post
尤为是可拓展性,发送请求到接收响应的过程当中的全部部分几乎都是可拓展的,尤为是config,adapter,interceptor留下了不少想象的空间。this