axios-rule-request - 基于axios的策略规则请求封装
axios-rule-request
axios 规则请求封装
简介
axios 二次封装 npm 包,增强。
平时使用 axios 请求接口,针对不同后端提供的接口,可能返回的数据格式不同,同时处理逻辑也不同,会造成编写不同的逻辑代码。
这个包把 axios 公共的请求逻辑和拦截器进行整合,并暴露出业务逻辑处理配置,减少代码,使 axios 更好配置。
如何使用
插件声明后,会直接返回 axios 实例,直接调用 axios 自带方法即可。
import HttpRequest from 'axios-rule-request';
import { Toast } from 'vant';
const http = new HttpRequest(
{},
{},
function (msg) {
Toast(msg);
},
function (loadingState) {
console.log('loadingState', loadingState);
}
);
http.get(`baidu.com/foo`, {
customHeader: {
deviceId: 'foo',
},
});
资源下载
目前项目源文件也上传到了csdn,可下载看看:
https://download.csdn.net/download/u013556779/88582448
API
以下文件使用jsdoc生成
Classes
AxiosRuleRequest
Kind: global class
new AxiosRuleRequest(rule, config, toastFn, loadingFn)
Param | Type | Description |
---|---|---|
rule | Object | 请求规则 |
config | Object | axios 配置 |
toastFn | function | toast 函数 |
loadingFn | function | loading 函数 |
Example
const axiosRuleRequest = new AxiosRuleRequest(
{
service: {
request: config => {
config.url = `${config.url}`;
return config;
},
response: res => {
if (res.code === 200) {
return res.data;
}
return Promise.reject(res);
},
},
},
{
baseURL: 'https://www.easy-mock.com/mock/5b6b7b2ce0dc663d7b2e8b8a/example',
},
msg => {
Toast(msg);
},
show => {
if (show) {
Toast.loading('加载中...', 0);
} else {
Toast.hide();
}
}
);
axiosRuleRequest.getInstance() ⇒ Object
获取 axios 实例
Kind: instance method of AxiosRuleRequest
Returns: Object
- axios 实例
Example
const axiosInstance = axiosRuleRequest.getInstance();
axiosInstance.get('/api/test');
axiosRuleRequest.setRule(rule, cover)
设置请求规则
Kind: instance method of AxiosRuleRequest
Access: public
Param | Type | Default | Description |
---|---|---|---|
rule | Object | 请求规则 | |
cover | Boolean | false | 是否覆盖 |
Example
axiosRuleRequest.setRule({
service: {
request: (config) => {
config.url = `${config.url}`;
return config;
},
response: (res) => {
if (res.code === 200) {
return res.data;
}
}
});
axiosRuleRequest.setLoadingFn(fn)
设置 loading 函数
Kind: instance method of AxiosRuleRequest
Access: public
Param | Type | Description |
---|---|---|
fn | function | loading 函数 |
Example
axiosRuleRequest.setLoadingFn(show => {
if (show) {
Toast.loading('加载中...', 0);
} else {
Toast.hide();
}
});
axiosRuleRequest.setToastFn(fn)
设置 toast 函数
Kind: instance method of AxiosRuleRequest
Access: public
Param | Type | Description |
---|---|---|
fn | function | toast 函数 |
Example
axiosRuleRequest.setToastFn(msg => {
Toast(msg);
});
初始化
Kind: global class