Skip to content

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。

查看源码
vue
<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。

查看源码
vue
<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 网络记录。

查看源码
vue
<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) 区分取消与真实失败。

查看源码
vue
<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 维护。

查看源码
vue
<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 百分比。

查看源码
vue
<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 时由平台决定落地位置。

查看源码
vue
<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?: HttpConfigHttpInstance-
request通用入口,url 必填config: HttpRequestConfigPromise<any>-
get / delete / head读请求,查询参数走 paramsurl: string, params?: JsonObject, config?: HttpCallConfigPromise<any>-
post / put / patch写请求,请求体走 dataurl: string, data?: JsonObject | string, config?: HttpCallConfigPromise<any>-
setDefaults增量更新实例默认配置patch: HttpConfigvoid-
abortController新建取消控制器-HttpAbortController-
isCancel判断是否为取消错误,直接传 catch 到的错误error: HttpError | nullboolean-
upload上传文件input: UploadInputPromise<UploadResult>-
download下载文件input: DownloadInputPromise<DownloadResult>-

实例不能直接调用

TS 没有 callable object,http(config) 非法,必须写成 http.request(config)。

实例配置 HttpConfig ​

create 入参与 setDefaults 补丁同型,未传字段沿用父级默认值。

字段说明类型默认值版本
baseURL基础地址,空串表示直接用 urlstring''-
headers默认请求头,与父级合并后按小写归一去重JsonObject | null{}-
timeout超时毫秒数number60000-
validateStatus状态码判定,默认 2xx 放行(status: number) => boolean2xx-
meta默认元信息,只透传给拦截器HttpMetaInput{ toast: false, loading: false }-

请求配置 ​

request() 的入参是 HttpRequestConfig;get / post 等方法第三参是 HttpCallConfig,url / method / params / data 由方法本身决定,不允许再传。

字段说明类型默认值版本
url请求地址,HttpRequestConfig 必填string--
method请求方法,非法值告警后回退 GETstring | nullGET-
headers本次请求头,覆盖实例默认值JsonObject | null--
params查询参数,仅 HttpRequestConfig 可用JsonObject | null--
data请求体,仅 HttpRequestConfig 可用JsonObject | string | null--
timeout本次超时,覆盖实例默认值number60000-
validateStatus本次状态码判定(status: number) => boolean2xx-
meta本次元信息,逐字段覆盖实例默认值HttpMetaInput--
signal取消凭证HttpAbortSignal | nullnull-

拦截器 ​

成员说明签名版本
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-
statusHTTP 状态码number-
headers响应头any-
cookies响应 cookieArray<string>-
config本次请求的最终配置ResolvedHttpConfig-

错误 HttpError ​

字段说明类型版本
code错误分类:ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTORstring-
message可展示的错误描述string-
statusHTTP 状态码,0 表示无响应number-
data响应体,有响应时非空any-
errCode平台原始错误码,网络错误时有效number-
config本次请求的最终配置ResolvedHttpConfig-
response有 HTTP 响应时非空HttpResponse | null-

上传与下载 ​

参数说明类型默认值版本
url请求地址string--
filePath上传必填;下载可选,不传返回临时路径string | null--
name上传表单字段名string | nullfile-
formData上传附加表单字段JsonObject | null--
headers本次请求头JsonObject | null--
timeout本次超时number60000-
meta本次元信息HttpMetaInput--
signal取消凭证HttpAbortSignal | nullnull-
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,失败也 reject HttpError。
  • 取消判断统一用 http.isCancel(e);不要写 e is HttpError 之类的类型判断,H5 转译后会变成未定义标识符。
  • 已 abort 的 signal 再次发起请求会立即 reject ERR_CANCELED,需要新请求时请新建控制器。