app-http-utils
v1.0.7
Published
# install ``` npm i -S app-http-utils ```
Downloads
6
Readme
app-http-utils
install
npm i -S app-http-utils
interface
interface RequestParams {
url?: string,
baseUrl?: string,
timeout?: number, // 超时时间,单位毫秒
method?: 'get' | 'post' | 'put' | 'delete' | 'head' | 'options' | 'trace' | 'patch',
headers?: { [key: string]: any };
data?: { [key: string]: any }; // 请求参数
files?: { [key: string]: any }; // 上传的文件
dataType?: 'json' | 'text';
}
interface Request {
execute(params: { loading?: boolean, toast?: boolean, config?: RequestParams }): Promise<any>,
cancel(): void;
}
interface RequestData {
(data?: { [key: string]: any }, files?: { [key: string]: any }): Request;
}
interface Http<T = any> {
(params: { loading?: boolean, toast?: boolean, config: RequestParams }): {
request(): Promise<T>,
cancel?(): void;
}
}
methods
ajax(url: string, config?: RequestParams): RequestData; get(url: string, config?: RequestParams): RequestData; post(url: string, config?: RequestParams): RequestData; setRequest(fun: Http): void
use
import HttpUtils from 'app-http-utils';
const defaultBaseUrl = 'https://www.baidu.com/';
const http = new HttpUtils<{ code: number, msg: string, data: any }>();
// 设置request请求执行方法
http.setRequest(({ loading, config }) => {
return {
request() {
const session = api.require('session');
return new Promise((res) => {
const baseUrl = config.baseUrl || defaultBaseUrl;
const timeout = config.timeout || 10000;
api.ajax({
url: baseUrl + config.url,
method: config.method,
timeout,
dataType: config.dataType,
headers: {
...config.headers
},
data: {
body: {
...config.data,
token: session.getToken()
}
}
}, (ret, err) => {
res(ret || err);
});
});
}
}
});
// 构建请求
const ajax = http.get<string>('s', { dataType: 'text' });
// 传递请求参数
const request = ajax({ wd: 'ooo' });
// 执行请求
request.execute().then(res=>{
console.log(res)
});