# 网络请求
系统的网络请求通过Axios
实现,我们对其进行的额外的封装:
- 自动携带
token
- 无感刷新
token
- 携带当前语言
- 可选的 Loading
- 自动取消重复请求
- 自动错误/成功提示
- 异常处理
TIP
1、在BuildAdmin
的/web/src/api/
目录,存放了系统所有的网络请求函数,我们也建议您将封装的请求函数放置于此目录下。
2、封装的createAxios
无法满足您的使用场景时,当然是可以直接使用axios.create
的,BuildAdmin对Axios的封装只是为了方便使用。
Axios
封装代码位于:/src/utils/axios.ts
,通常您参考如下方式创建请求即可:
createAxios(axiosConfig: AxiosRequestConfig, options: Options = {}, loading: LoadingOptions = {}): ApiPromise | AxiosPromise
# 基本使用示例
import createAxios from '/@/utils/axios'
export function getMenuRules() {
return createAxios({
url: '/index.php/admin/auth.menu/index',
method: 'get',
})
}
// 然后就可以
getMenuRules().then((res) => {
console.log(res)
})
# 参数解释
# 参数一:axiosConfig
axiosConfig
参数用于配置:Axios
创建请求时自带的可用配置选项,可用配置项请参考Axios网站 (opens new window),只有url
是必需的,默认请求方法为get
。
createAxios({
url: '/index.php/admin/auth.menu/index',
method: 'get',
timeout: 3000, // 请求超时毫秒数,可覆盖默认的超时设定
// ...
})
# 参数二:options
options
参数可以传递以下可用选项:
选项名 | 默认值 | 注释 |
---|---|---|
CancelDuplicateRequest | true | 是否开启取消重复请求(连续的重复请求会被自动取消) |
loading | false | 是否开启loading 层效果 |
reductDataFormat | true | 是否开启简洁的数据结构响应(开启返回ApiPromise ,关闭返回AxiosPromise ) |
showErrorMessage | true | 是否开启接口错误信息直接提示,如接口404 |
showCodeMessage | true | 是否开启code!=0 时的信息直接提示(比如操作失败直接弹窗提示接口返回的消息,就不需要再写代码弹窗提示了) |
showSuccessMessage | false | 是否开启code=0 时的信息直接提示 |
// 此处,我们为请求方法确定了返回类型,以此得到更好的类型支持,本操作是可选的
export function postData(data: anyObj): ApiPromise<TableDefaultData> {
return createAxios(
{
url: actionUrl.get('edit'),
method: 'post',
data: data,
},
{
showSuccessMessage: true,
}
) as ApiPromise
}
# 参数三:loading
我们封装了element
的loading
,此参数用于设置loading
的配置,所有可用配置项,请参考官方文档 (opens new window)。
// 示例一
export function postData(data: anyObj) {
return createAxios(
{
url: actionUrl.get('edit'),
method: 'post',
data: data,
},
{},
{
text: '正在全力提交中...'
}
)
}
// 示例二
export function getMenuRules() {
return createAxios(
{
url: '/index.php/admin/auth.menu/index',
method: 'get',
},
{},
{
text: '正在全力加载中...'
}
)
}