business-request
网络请求库,基于 axios 封装,旨在提供一个统一的 api 调用方式, 简化使用。
安装
npm install --save @winner-fed/business-request
快速上手
基础参数配置
import {createRequest} from '@winner-fed/business-request';
const api = createRequest({
baseURL: 'https://api.github.com/',
timeout: 3000
)};
GET 请求
api
.get('/users/octocat?_t=' + Date.now())
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
// 也可将 URL 的参数放到 options.params 里
api
.get('/users/octocat', {
params: {
_t: Date.now(),
},
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
POST 请求
api
.post('/users/octocat', {
name: 'Mike',
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
business-request API
request(url[, options])
api.request('/api/v1/xxx', {
method: 'get',
params: { id: 1 },
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
request('/api/v1/user', {
method: 'post',
data: {
name: 'Mike',
},
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
请求方法的别名
为了方便起见,为所有支持的请求方法提供了别名, method
属性不必在配置中指定
api.request(url[, CreateAxiosOptions])
api.get(url[, CreateAxiosOptions])
api.post(url[, data[, CreateAxiosOptions])
api.delete(url[, data[, CreateAxiosOptions])
api.put(url[, data[, CreateAxiosOptions])
interface CreateAxiosOptions extends AxiosRequestConfig {
prefix?: string;
suffix?: string;
requestType?: string;
transform?: AxiosTransform;
joinParamsToUrl?: boolean;
isTransformRequestResult?: boolean;
isTransformResponseResult?: boolean;
isDebug?: boolean
}
abstract class AxiosTransform {
transformResponseData?: (res: AxiosResponse, config: CreateAxiosOptions) => any;
requestInterceptors?: (config: CreateAxiosOptions) => CreateAxiosOptions;
requestInterceptorsCatch?: (error: Error) => void;
responseInterceptors?: (res: AxiosResponse) => AxiosResponse;
responseInterceptorsCatch?: (error: Error) => void;
errorHandler?: (e: Error) => Promise<any>;
}
请求参数配置
axios 其他请求配置参数详见,https://github.com/axios/axios#request-config
{
method: 'get',
params: { id: 1 },
data: { name: 'Mike' },
headers: { 'Content-Type': 'application/json' },
timeout: 25000,
prefix: '',
suffix: '',
requestType: 'json',
isTransformResponseResult: true,
isDebug: true,
responseType: 'json',
transform: {
transformResponseData (res: AxiosResponse, config: CreateAxiosOptions) => void
requestInterceptors (config: CreateAxiosOptions) => CreateAxiosOptions;
requestInterceptorsCatch?: (error: Error) => void;
responseInterceptors?: (res: AxiosResponse) => AxiosResponse;
responseInterceptorsCatch?: (error: Error) => void;
errorHandler?: (error) { },
}
}
其他方法
setBaseURL(baseURL: string): void
setHeader(headers: any): void
TODO
- 支持公共参数配置,如data,也支持具体请求参数覆盖
- 请求数据拦截(扩展性),响应数据拦截