http 请求
17:43说明
http 是 axios 形态的请求实例:http.create(config) 派生独立实例并深合并默认值,请求 / 响应双向拦截器可解包也可统一处理错误,内建超时、状态码判定、取消与上传下载进度,配合 useRequest 拿到 loading / data / error 三态,失败一律 reject HttpError。
核心能力
零第三方依赖,只基于 uni.request / uni.uploadFile / uni.downloadFile,App、H5、小程序同一套写法。
| 能力 | 支持情况 |
|---|---|
| 实例派生 | http.create(config) 派生独立实例,深合并父级默认值 —— 多域名 / 多服务各建一个 |
| 请求方法 | request 通用入口,另有 get / delete / head / post / put / patch 方法糖 |
| 拦截器 | 请求链与响应链,多次 use 追加成链、按注册顺序执行;请求链可中断,响应链可解包或统一处理错误 |
| 配置覆盖 | baseURL / headers / timeout / validateStatus / meta 均可实例级设默认、单次请求覆盖 |
| 超时 | 实例默认值 + 单次请求覆盖,默认 60000ms |
| 状态码判定 | validateStatus(status) 自定义放行规则,默认 2xx 成功 |
| 请求取消 | abortController() 生成控制器,signal 随请求传入;isCancel(e) 区分取消与真实失败 |
| 上传 / 下载 | upload / download 带 0-100 进度回调,与普通请求共用同一套默认值、拦截器与错误模型 |
| 页面三态 | useRequest 提供 loading / data / error,内置竞态丢弃、重跑先取消、卸载自动取消 |
| 元信息透传 | meta(如 toast / loading)只给拦截器看,用于统一提示、骨架与埋点 |
| 错误分类 | HttpError.code 四类:ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTOR |
亮点:
- 不隐藏响应:默认拿到完整
HttpResponse(data/status/headers/cookies/config都在),要不要解包由你的响应拦截器决定,需要按状态码分流的场景不用二次改造。 - 拦截器是数组链:连续
use即叠加,注册顺序就是执行顺序;请求链返回null即中断本次请求,不必额外定义「跳过」标记。 - 上传下载同一套语义:不是另开一套 API ——
upload/download同样经过请求拦截器与validateStatus,失败同样是HttpError,可共用同一份错误提示逻辑。 - 取消是一等能力:
abortController与useRequest打通,页面卸载自动取消;isCancel兜住「取消不等于出错」这个高频判断点。
兼容性
| 平台 | 支持 | 说明 |
|---|---|---|
| App | ✅ 支持 | 基于 uni.request / uni.uploadFile / uni.downloadFile |
| H5 | ✅ 支持 | 下载返回 blob 临时路径;跨域请求需服务端允许 CORS |
| 微信小程序 | ✅ 支持 | 需在小程序后台配置 request / uploadFile / downloadFile 域名 |
示例
基础 GET
get(url, params) 的 params 序列化后拼到查询串,默认 resolve 完整响应,取业务数据前先看 status。
查看源码
<template>
<ux-button text="发起 GET" type="primary" shape="round" @click="runGet" />
<demo-result :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
import type { HttpResponse } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
const api = http.create({ baseURL: 'https://httpbin.org' });
const runGet = (): void => {
const params = new JsonObject();
params['demo'] = 'uview-pro-x';
params['page'] = 1;
api.get('/get', params).then((res: any) => {
const response = res as HttpResponse;
const body = response.data as JsonObject;
text.value = 'HTTP ' + response.status.toString() + ' · ' + (body['url'] as string);
}).catch((e: any) => {
text.value = e.message;
});
};
</script>POST 与请求拦截器
请求拦截器以数组链存放,多次 use 追加、按注册顺序执行,返回 null 中断本次请求并 reject ERR_CANCELED。
查看源码
<template>
<ux-button text="发起 POST" type="success" shape="round" @click="runPost" />
<demo-result type="success" :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
import type { HttpResponse } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
const api = http.create({ baseURL: 'https://httpbin.org' });
// 请求拦截器:数组链,按注册顺序执行
api.interceptors.request.use((config) => {
config.headers['x-demo-source'] = 'uview-pro-x';
return config;
});
const runPost = (): void => {
const payload = new JsonObject();
payload['title'] = 'uview-pro-x';
payload['body'] = 'http demo';
payload['userId'] = 1;
api.post('/post', payload).then((res: any) => {
const body = (res as HttpResponse).data as JsonObject;
const echo = body['json'] as JsonObject;
text.value = (echo['title'] as string);
}).catch((e: any) => {
text.value = e.message;
});
};
</script>HTTP 错误
非 2xx 状态码 reject ERR_BAD_RESPONSE,status 为真实状态码,原始响应保留在 error.response 里。
H5 端说明
错误响应体为空或非 JSON 时,运行时会在控制台打印一条 JSON 解析告警(业务错误照常 reject,不影响处理)。示例特意选用返回 JSON 体的 404 接口,控制台只保留预期的 404 网络记录。
查看源码
<template>
<ux-button text="请求 404" type="error" shape="round" @click="runError" />
<demo-result type="error" :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
import type { HttpError } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
// 错误接口 404 且返回 JSON 体:H5 端空响应体的 404 会伴随一条 JSON 解析告警
const errorApi = http.create({ baseURL: 'https://gitee.com/api/v5' });
const runError = (): void => {
errorApi.get('/repos/uview-pro-x/not-found').then((res: any) => {
text.value = '未预期的成功';
}).catch((e: any) => {
const err = e as HttpError;
// code: ERR_BAD_RESPONSE;status: 404;response 里保留原始响应
text.value = err.code + ' · HTTP ' + err.status.toString();
});
};
</script>取消请求
abortController() 创建控制器,把 signal 随请求传入,调用 abort() 后请求以 ERR_CANCELED reject,用 http.isCancel(e) 区分取消与真实失败。
查看源码
<template>
<ux-button text="发起并取消" type="warning" shape="round" @click="runCancel" />
<demo-result type="warning" :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
import type { HttpCallConfig } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
const runCancel = (): void => {
// 每次点击新建控制器,避免复用已 abort 的 signal
const controller = http.abortController();
setTimeout(() => {
controller.abort();
}, 300);
http.get('https://httpbin.org/delay/5', null, { signal: controller.signal } as HttpCallConfig).then((res: any) => {
text.value = '取消失败:请求已完成';
}).catch((e: any) => {
text.value = http.isCancel(e) ? '已取消(ERR_CANCELED)' : e.message;
});
};
</script>useRequest
useRequest 只在 fetcher 里用 ctx.signal 透传取消能力,三态与竞态丢弃由 Hook 维护。
查看源码
<template>
<ux-button text="通过 useRequest 请求" type="primary" shape="round" @click="run" />
<demo-result :text="summary" />
</template>
<script setup lang="ts">
import { http, useRequest } from '@/uni_modules/uview-pro-x';
import type { HttpCallConfig, HttpResponse } from '@/uni_modules/uview-pro-x';
const api = http.create({ baseURL: 'https://httpbin.org' });
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/uuid', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
const summary = computed<string>(() => {
if (detail.loading.value) return '请求中…';
const err = detail.error.value;
if (err != null) return err.message;
const data = detail.data.value;
if (data == null) return '待发起';
return data['uuid'] as string;
});
const run = (): void => {
detail.run();
};
</script>上传
upload 复用实例默认值与拦截器,content-type 会被剔除,multipart 边界由平台生成;进度回调给出 0-100 百分比。
查看源码
<template>
<ux-button text="选择图片上传" type="info" shape="round" @click="runUpload" />
<demo-result :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
const runUpload = (): void => {
uni.chooseImage({
count: 1,
success: (res) => {
const paths = res.tempFilePaths;
if (paths.length == 0) return;
http.upload({
url: 'https://httpbin.org/post',
filePath: paths[0],
name: 'file',
onProgress: (p) => {
text.value = p.progress.toString() + '%';
}
}).then((result) => {
text.value = 'HTTP ' + result.status.toString();
}).catch((e: any) => {
text.value = e.message;
});
}
});
};
</script>下载
download 返回临时文件路径,App 端可再复制到业务目录;不传 filePath 时由平台决定落地位置。
查看源码
<template>
<ux-button text="下载图片" type="info" shape="round" @click="runDownload" />
<demo-result :text="text" />
</template>
<script setup lang="ts">
import { http } from '@/uni_modules/uview-pro-x';
const text = ref<string>('待发起');
const runDownload = (): void => {
http.download({
url: 'https://httpbin.org/image/png',
onProgress: (p) => {
text.value = p.progress.toString() + '%';
}
}).then((result) => {
text.value = result.tempFilePath;
}).catch((e: any) => {
text.value = e.message;
});
};
</script>API
实例方法
http 与 http.create() 的产物同型,下表方法在两者上都可用。
| 方法 | 说明 | 参数 | 返回值 | 版本 |
|---|---|---|---|---|
| create | 派生新实例:继承当前 defaults(深合并),不继承拦截器 | config?: HttpConfig | HttpInstance | - |
| request | 通用入口,url 必填 | config: HttpRequestConfig | Promise<any> | - |
| get / delete / head | 读请求,查询参数走 params | url: string, params?: JsonObject, config?: HttpCallConfig | Promise<any> | - |
| post / put / patch | 写请求,请求体走 data | url: string, data?: JsonObject | string, config?: HttpCallConfig | Promise<any> | - |
| setDefaults | 增量更新实例默认配置 | patch: HttpConfig | void | - |
| abortController | 新建取消控制器 | - | HttpAbortController | - |
| isCancel | 判断是否为取消错误,直接传 catch 到的错误 | error: HttpError | null | boolean | - |
| upload | 上传文件 | input: UploadInput | Promise<UploadResult> | - |
| download | 下载文件 | input: DownloadInput | Promise<DownloadResult> | - |
实例不能直接调用
TS 没有 callable object,http(config) 非法,必须写成 http.request(config)。
实例配置 HttpConfig
create 入参与 setDefaults 补丁同型,未传字段沿用父级默认值。
| 字段 | 说明 | 类型 | 默认值 | 版本 |
|---|---|---|---|---|
| baseURL | 基础地址,空串表示直接用 url | string | '' | - |
| headers | 默认请求头,与父级合并后按小写归一去重 | JsonObject | null | {} | - |
| timeout | 超时毫秒数 | number | 60000 | - |
| validateStatus | 状态码判定,默认 2xx 放行 | (status: number) => boolean | 2xx | - |
| meta | 默认元信息,只透传给拦截器 | HttpMetaInput | { toast: false, loading: false } | - |
请求配置
request() 的入参是 HttpRequestConfig;get / post 等方法第三参是 HttpCallConfig,url / method / params / data 由方法本身决定,不允许再传。
| 字段 | 说明 | 类型 | 默认值 | 版本 |
|---|---|---|---|---|
| url | 请求地址,HttpRequestConfig 必填 | string | - | - |
| method | 请求方法,非法值告警后回退 GET | string | null | GET | - |
| headers | 本次请求头,覆盖实例默认值 | JsonObject | null | - | - |
| params | 查询参数,仅 HttpRequestConfig 可用 | JsonObject | null | - | - |
| data | 请求体,仅 HttpRequestConfig 可用 | JsonObject | string | null | - | - |
| timeout | 本次超时,覆盖实例默认值 | number | 60000 | - |
| validateStatus | 本次状态码判定 | (status: number) => boolean | 2xx | - |
| meta | 本次元信息,逐字段覆盖实例默认值 | HttpMetaInput | - | - |
| signal | 取消凭证 | HttpAbortSignal | null | null | - |
拦截器
| 成员 | 说明 | 签名 | 版本 |
|---|---|---|---|
| interceptors.request.use | 请求拦截器,返回 null 中断请求 | (fn: (config: ResolvedHttpConfig) => ResolvedHttpConfig | null) => void | - |
| interceptors.response.use | 响应拦截器,可选错误处理 | (onFulfilled: (response: HttpResponse) => any, onRejected?: (error: HttpError) => HttpError) => void | - |
响应链里每个 onFulfilled 收到同一个 HttpResponse,最后一个非 null 返回值作为最终 resolve 值;onRejected 按注册顺序执行,最后一个返回值生效。
响应 HttpResponse
| 字段 | 说明 | 类型 | 版本 |
|---|---|---|---|
| data | 响应体,形状由服务端决定 | any | - |
| status | HTTP 状态码 | number | - |
| headers | 响应头 | any | - |
| cookies | 响应 cookie | Array<string> | - |
| config | 本次请求的最终配置 | ResolvedHttpConfig | - |
错误 HttpError
| 字段 | 说明 | 类型 | 版本 |
|---|---|---|---|
| code | 错误分类:ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTOR | string | - |
| message | 可展示的错误描述 | string | - |
| status | HTTP 状态码,0 表示无响应 | number | - |
| data | 响应体,有响应时非空 | any | - |
| errCode | 平台原始错误码,网络错误时有效 | number | - |
| config | 本次请求的最终配置 | ResolvedHttpConfig | - |
| response | 有 HTTP 响应时非空 | HttpResponse | null | - |
上传与下载
| 参数 | 说明 | 类型 | 默认值 | 版本 |
|---|---|---|---|---|
| url | 请求地址 | string | - | - |
| filePath | 上传必填;下载可选,不传返回临时路径 | string | null | - | - |
| name | 上传表单字段名 | string | null | file | - |
| formData | 上传附加表单字段 | JsonObject | null | - | - |
| headers | 本次请求头 | JsonObject | null | - | - |
| timeout | 本次超时 | number | 60000 | - |
| meta | 本次元信息 | HttpMetaInput | - | - |
| signal | 取消凭证 | HttpAbortSignal | null | null | - |
| onProgress | 进度回调,progress 为 0-100 | (p: TransferProgress) => void | - | - |
TransferProgress 字段:progress(0-100)、transferred(已传输字节)、total(总字节)。上传返回 UploadResult { data: string, status: number },下载返回 DownloadResult { tempFilePath: string, status: number }。
注意事项
create只继承defaults,拦截器需要在派生实例上重新注册。GET/HEAD的data会被忽略并告警,查询参数一律用params。validateStatus只接受函数,需要放行所有状态码时传(): boolean => true,不支持传null。upload会在合并后剔除content-type,由平台生成带boundary的multipart头。- 上传、下载同样经过请求拦截器与
validateStatus,失败也 rejectHttpError。 - 取消判断统一用
http.isCancel(e);不要写e is HttpError之类的类型判断,H5 转译后会变成未定义标识符。 - 已
abort的signal再次发起请求会立即 rejectERR_CANCELED,需要新请求时请新建控制器。