@chaoswise/request
v1.2.12
Published
公共请求库
Downloads
351
Keywords
Readme
公共请求库
Features
- 统一公共请求,作为单独的包运行,相当于axios的再次封装
- 支持mock数据
- 多次重复请求,保留最后一次请求(可通过cancelRepeat配置关闭)
- 封装cancel方法
API
// 全部api引用方法
import {
initRequest,
mockInstance,
axiosInstance,
clearPending,
pending,
fetchGet,
fetchPut,
fetchDelete,
fetchPost,
upload,
downloadFile,
formateResponse
} from '@chaoswise/request';
1. initRequest
2. mockInstance
3. axiosInstance
4. clearPending
5. pending
6. fetchGet
7. fetchPut
8. fetchDelete
9. fetchPost
10. upload
11. downloadFile
12. formateResponse
initRequest
初始化配置并创建请求实例axiosInstance
initRequest({
config: {
// 请求错误码回调
statusCallback: {
'401': () => {
},
'403': () => {
}
},
// 是否启用mock数据 false 关闭 true 开启
useMock: true,
// mock延迟mm
delayResponse: 500,
// 统一处理请求
handleResponse: (res, error) => {
if (error) {
// 错误处理
} else {
// 响应处理
}
},
// 是否开启登陆验证 false 关闭 true 开启(统一处理401登出逻辑)
checkLogin: false,
// restapi: sso登出校验地址
restapi: '', // 默认为 error.response.config.url 设置后以设置为准
},
// 请求头的配置文件
defaults: {
// 请求的基础域名
baseURL: "",
},
// mock模拟请求接口数组, 依赖axios-mock-adapter,约定生成相关mock接口,也可通过mockInstance参考官方api实现mock数据
mock: [{
method: 'onGet',
url: 'mockurl',
res: {
code: 100000,
data: {}
}
}]
});
mockInstance
mock数据实例,参考axios-mock-adapter
// 模拟分页接口demo
import { mockInstance } from '@chaoswise/request';
import { demoListData } from './demoListConfig';
mockInstance.onGet("/get/basictablelist").reply((config) => {
let filterData = demoListData;
let resultData = [];
let totalNum = 0;
let currentPage = config.params.currentPage;
let pageSize = config.params.pageSize;
totalNum = filterData.length;
resultData = filterData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
return [200, {
data: resultData,
total: totalNum
}];
});
axiosInstance
axios实例,参考axios
// Add a request interceptor
axiosInstance.interceptors.request.use(function (config) {
// Do something before request is sent
// 统一增加国际化标识
config.headers.language = langUtil.getLang().language;
const isDev = process.env.NODE_ENV === 'development';
if (window.DOSM_CONFIG.isIgnoreGetway && isDev) {
config.headers = {
...config.headers,
accountId: '110',
userId: '2',
topAccountId: '110',
};
}
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
clearPending
中断所有请求
import { clearPending, fetchPost } from '@chaoswise/request';
// 取消全部已发出请求(例如:页面销毁)
clearPending()
// 指定已请求方法取消
const method1 = fetchPost('/get/list')
method1.cancel();
pending
全部请求根据请求url存储到一个map中,里面包含cancel方法(此方法使用场景不多,大部分场景可以通过clearPending下的场景实现)
import { pending } from '@chaoswise/request';
// 中断某一请求
const cancel = pending.get('/demo/api/v1');
cancel('/demo/api/v1');
pending.delete('/demo/api/v1')
fetchGet
get请求
import { fetchGet } from '@chaoswise/request';
fetchGet('/get/basictablelist', {
params: {
name: '张三'
}
}).then(res => {
// 成功
}).catch(err => {
// 失败
})
fetchPut
put请求
import { fetchPut } from '@chaoswise/request';
fetchPut('/get/basictablelist', {
data: {
name: '张三'
}
}).then(res => {
// 成功
}).catch(err => {
// 失败
})
fetchDelete
put请求
import { fetchDelete } from '@chaoswise/request';
fetchDelete('/get/basictablelist', {
data: {
name: '张三'
}
}).then(res => {
// 成功
}).catch(err => {
// 失败
})
fetchPost
put请求
import { fetchPost } from '@chaoswise/request';
fetchPost('/get/basictablelist', {
data: {
name: '张三'
}
}).then(res => {
// 成功
}).catch(err => {
// 失败
})
upload
文件上传
import { upload } from '@chaoswise/request';
upload (
'http:xxx', // 请求url
{}, // 请求参数
() => {}, // 上传进度回调
{} // 其它请求实例可能要透传的参数
).then(res => {
// 成功
}).catch(err => {
// 失败
})
downloadFile
文件下载,默认下载excel
import { downloadFile } from '@chaoswise/request';
downloadFile(
content, // 内容
filename, // 文件名称
{
type: '下载文件类型'
}, // 参数
)
formateResponse
- 后端接口返回数据格式化,
- 参数response是请求返回值,
- 将返回值error_code转code,error_msg转msg,
- 最终返回{code:10000,status:'success',data:null,msg:'**'}
import { formateResponse } from '@chaoswise/request';
const res = formateResponse({
error_code:000000,
error_msg:"success",
data:{}
})
console.log(res);
/*
res = {
code:100000,
msg:"success",
status:"success",
data:{}
}
mock方法
1. 约定式
在初始化实例进行配置
//
initRequest({
mock: [[
{
"method": "onGet",
"url": "/get/list",
"res": {
"code": 100000,
"data": 141314
}
},
{
"method": "onGet",
"url": "/get/auth",
"res": {
"status": "success",
"msg": null,
"code": 100000,
"data": [
{
"code": "1011000101",
"selected": true
},
{
"code": "11",
"selected": true
}
]
}
}
]]
})
使用mock实例进行注册(具体参考axios-mock-adapter)
import { mockInstance } from '@chaoswise/request';
mockInstance.onGet("/get/allUser").reply(200, {
data: "get 获取的全部用户 [user1, user2, user3]"
});
mockInstance.onPost("/get/allUser").reply(200, {
data: "post 获取的全部用户 [user1, user2, user3]"
});
mockInstance.onGet("/get/user", {
params: {
id: 'user1'
}
}).reply(200, {
data: "get 获取的到的用户为: user1"
});
mockInstance.onPost("/get/user", {
id: 'user1'
}).reply(200, {
data: "post 获取的到的用户为: user1"
});