API
静态成员
create() important
important
用法与
axios.create()
基本相同,用于创建一个 http-sluggard 实例(单例模式)
- 类型
ts
function create<T extends MethodAlias>(
requestConfig?: RequestConfig,
initConfig?: {
methodAlias?: MethodAlias;
life?: LifeType;
}): HttpIns<T>
interface MethodAlias {
[aliasName: string]: {
axiosMethod: AxiosMethodsName
handle: MethodAliasHandle
}
}
interface LifeType {
begin?: (config: HttpConfig) => void
end?: () => void
}
详细信息
- 第一个参数与
axios.create()
的config
参数一致,详见AxiosRequestConfig
- 第二个参数
initConfig
为 sluggard-http 配置参数,包含两个部分:
- 第一个参数与
示例
ts
import NProgress from "nprogress";
import { Http } from 'sluggard-http';
import type { MethodAlias, RequestConfig } from 'sluggard-http';
const methodAlias = {
download: {
axiosMethod: 'post',
handle: (url: string, data: any, config: RequestConfig) => {
return [url, data, { ...config, responseType: 'blob' }]
},
},
} as const
export const http = Http.create<typeof methodAlias>(
{
baseURL: '...',
timeout: 1000,
headers: {'Authorization': '...'}
},
{
methodAlias,
life: {
begin: () => {
NProgress.start()
},
end: () => {
NProgress.done()
},
},
}
)
axiosIns
原始 axios 实例对象,一般不需要使用
- 类型
ts
const axiosIns: AxiosInstance
实例方法
clearPending()
清除并
取消
当前所有的请求, 往往在路由
变化时使用
可在请求时配置canNotClear
避免清除
- 示例
ts
http.clearPending()
abortPending()
对还在
进行中
的指定
请求进行拦截, 并取消
请求
无视canNotClear
配置
- 类型
TS
function abortPending(abortSign?: AbortSign | string): void
type AbortSign = [AxiosMethodsName, string, object]
详细信息
参数为拦截标识,可以为以下类型:
名称 类型 释义 拦截标识符 string
通过请求返回的 HttpPromise
对象获取请求标识数组 AbortSign
由请求的 [请求方式, 请求地址, 请求参数]
组成的数组不带参数 undefined
拦截并取消所有未完成的请求
示例
TS
const { abortSignUuidCode } = http.post("/getList", { size: 10, current: 1 })
http.abortPending(abortSignUuidCode)
// OR
http.abortPending(["post", "/getList", { size: 10, current: 1 }]);
- 参考 内置功能 - 请求拦截
请求配置
RequestConfig
继承自
AxiosRequestConfig
,用于配置请求参数
- 类型
TS
interface RequestConfig extends AxiosRequestConfig {
updateLevel?: 'all' | 'path' | 'free'
canNotClear?: boolean
}
updateLevel
请求更新级别
字面量 级别名称 释义 all
(默认值)全量 请求方式
&请求地址
&query
&data
都相同时,视为相同请求
path
路径 请求方式
&请求地址
相同时,视为相同请求
free
自由 每次请求都被视为 不同请求
,不受请求更新控制,常用于统计计数类接口示例
TS
const q1 = http.post('/user', { firstName: 'Fred', lastName: 'Flintstone' })
const q2 = http.post('/user', { firstName: 'Fred', lastName: 'Flintstone' })
const q3 = http.post('/user', { firstName: 'George', lastName: 'Bush' })
all
模式下,q1
和q2
被视为同一请求,q3
被视为不同请求path
模式下,q1
、q2
、q3
都被视为同一请求free
模式下,q1
、q2
、q3
都被视为不同请求
- 使用
TS
// 无需配置 默认为 all 级别 👇
const httpRes = await http.post("/getList", data);
// 配置为 path 级别 👇
const httpRes = await http.post("/getList", data, { updateLevel: "path" });
// 配置为 free 级别 👇
const httpRes = await http.post("/getList", data, { updateLevel: "free" });
- 参考 内置功能 - 请求更新
canNotClear
- 能否被
clearPending()
清除 - 示例
TS
export async function getList(data: any) {
const httpRes = await http.post(
"/getList",
data,
{ canNotClear: true } // 不会被 clearPending() 清除
);
return httpRes;
}