这一章主要实现接口的扩展
接口扩展
目录结构:
core 目录:
core 中的都是一些核心代码
Axios.ts
这个是新加的类,扩展接口,可以向 axios,axios.get,axios.post 那样使用
import {AxiosRequestConfig, AxiosPromise,Method} from '../types'
import dispatchRequest from './dispatchRequest';
export default class Axios{
request(config:AxiosRequestConfig):AxiosPromise {
return dispatchRequest(config);
}
get(url:string,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithoutData('get',url,config);
}
delete(url:string,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithoutData('delete',url,config);
}
head(url:string,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithoutData('head',url,config);
}
options(url:string,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithoutData('options',url,config);
}
post(url:string,data:any,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithData('post',url,data,config);
}
put(url:string,data:any,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithData('put',url,data,config);
}
patch(url:string,data:any,config?:AxiosRequestConfig) :AxiosPromise {
return this._requestMethodWithData('patch',url,data,config);
}
_requestMethodWithoutData(method: Method, url: string, config?:AxiosRequestConfig) : AxiosPromise {
return this.request(Object.assign(config || {} , {
method,
url
}))
}
_requestMethodWithData(method: Method, url: string,data:any, config?:AxiosRequestConfig) : AxiosPromise {
return this.request(Object.assign(config || {} , {
method,
url,
data,
}))
}
}
dispatchRequest.ts
import {AxiosRequestConfig,AxiosPromise, AxiosResponse} from '../types';
import xhr from './xhr';
import { buildURL } from '../helpers/url';
import {transformRequest,transformResponse} from '../helpers/data';
import { processHeaders } from '../helpers/header';
export default function dispatchRequst (config :AxiosRequestConfig) : AxiosPromise {
processConfig(config);
return xhr(config).then(res => {
return transformResponseData(re