Skip to content

http — Request ​

17:43

Description ​

http is an axios-shaped request instance: http.create(config) derives an independent instance with deep-merged defaults, request/response interceptors can unwrap payloads or handle errors in one place, and it ships timeout, status validation, cancellation and upload/download progress, plus useRequest for loading / data / error state — every failure rejects with HttpError.

Core Capabilities ​

No third-party dependencies: it only builds on uni.request / uni.uploadFile / uni.downloadFile, so App, H5 and Mini Program share one set of code.

CapabilityWhat you get
Instance derivationhttp.create(config) derives an independent instance with deep-merged defaults — one per host or service
Request methodsrequest as the general entry, plus get / delete / head / post / put / patch
InterceptorsRequest and response chains; each use appends and they run in registration order — the request chain can abort, the response chain can unwrap or handle errors
Config overridesbaseURL / headers / timeout / validateStatus / meta set per instance, overridable per call
TimeoutInstance default plus per-call override, 60000ms by default
Status validationvalidateStatus(status) for custom rules, 2xx by default
CancellationabortController() with signal; isCancel(e) tells cancellation from real failures
Upload / downloadupload / download with 0-100 progress callbacks, sharing defaults, interceptors and the error model
Page stateuseRequest exposes loading / data / error with stale-response dropping, cancel-on-rerun and cancel-on-unmount
Metadatameta (e.g. toast / loading) is visible to interceptors only, for global toasts, skeletons and tracking
Error modelHttpError.code is one of ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTOR

Highlights:

  • The response is not hidden — you get the full HttpResponse (data / status / headers / cookies / config); whether to unwrap it is your interceptor's decision, so status-based branching needs no rework.
  • Interceptors are array chains — successive use calls stack up in registration order; returning null from the request chain aborts that request, with no extra "skip" flag.
  • Upload and download follow the same semantics — they are not a separate API: they run through the same request interceptors and validateStatus, and reject with HttpError, so error handling is shared.
  • Cancellation is first-class — abortController works together with useRequest, which cancels on unmount; isCancel covers the common "cancel is not an error" check.

Compatibility ​

PlatformSupportNotes
App✅ SupportedBuilt on uni.request / uni.uploadFile / uni.downloadFile
H5✅ SupportedDownloads resolve to a blob temp path; cross-origin calls need CORS
WeChat Mini Program✅ SupportedAdd the request / uploadFile / downloadFile domains to the allowlist

Examples ​

Basic GET ​

get(url, params) serializes params into the query string and resolves with the full response; check status before reading business data.

View source
vue
<template>
    <ux-button text="Send 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>('Not started');
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 with request interceptor ​

Request interceptors are kept as an array chain: each use appends, handlers run in registration order, and returning null aborts the request with ERR_CANCELED.

View source
vue
<template>
    <ux-button text="Send 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>('Not started');
const api = http.create({ baseURL: 'https://httpbin.org' });

// Request interceptor: array chain, executed in registration order
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 error ​

A non-2xx status rejects with ERR_BAD_RESPONSE; status holds the real code and the raw response stays in error.response.

H5 note

When an error body is empty or not JSON, the runtime logs one JSON parse warning to the console (the business error still rejects as usual). The demo deliberately uses a 404 endpoint that returns a JSON body, so only the expected 404 network entry appears.

View source
vue
<template>
    <ux-button text="Request 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>('Not started');
// This 404 endpoint returns a JSON body: an empty 404 body logs a JSON parse warning on H5
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 = 'Unexpected success';
    }).catch((e: any) => {
        const err = e as HttpError;
        // code: ERR_BAD_RESPONSE; status: 404; response keeps the raw response
        text.value = err.code + ' · HTTP ' + err.status.toString();
    });
};
</script>

Cancel request ​

abortController() creates a controller: pass its signal with the request, then call abort(). The request rejects with ERR_CANCELED, and http.isCancel(e) tells a cancel apart from a real failure.

View source
vue
<template>
    <ux-button text="Send and cancel" 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>('Not started');

const runCancel = (): void => {
    // Create a controller per click so an aborted signal is never reused
    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 = 'Cancel failed: request already finished';
    }).catch((e: any) => {
        text.value = http.isCancel(e) ? 'Canceled (ERR_CANCELED)' : e.message;
    });
};
</script>

useRequest ​

useRequest only needs ctx.signal forwarded inside the fetcher; the hook maintains the three states and drops stale responses.

View source
vue
<template>
    <ux-button text="Request via 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 'Loading…';
    const err = detail.error.value;
    if (err != null) return err.message;
    const data = detail.data.value;
    if (data == null) return 'Not started';
    return data['uuid'] as string;
});

const run = (): void => {
    detail.run();
};
</script>

Upload ​

upload reuses the instance defaults and interceptors, drops content-type so the platform can build the multipart boundary, and reports progress as 0-100.

View source
vue
<template>
    <ux-button text="Pick and upload" 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>('Not started');

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 ​

download resolves with a temp file path that can be copied into app storage; without filePath the platform decides where the file lands.

View source
vue
<template>
    <ux-button text="Download image" 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>('Not started');

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 ​

Instance methods ​

http and the result of http.create() share the same shape, so every method below is available on both.

MethodDescriptionParametersReturnsVersion
createDerives a new instance: inherits defaults (deep merged), not interceptorsconfig?: HttpConfigHttpInstance-
requestGeneric entry, url is requiredconfig: HttpRequestConfigPromise<any>-
get / delete / headRead requests, query values go through paramsurl: string, params?: JsonObject, config?: HttpCallConfigPromise<any>-
post / put / patchWrite requests, body goes through dataurl: string, data?: JsonObject | string, config?: HttpCallConfigPromise<any>-
setDefaultsMerges a patch into the instance defaultspatch: HttpConfigvoid-
abortControllerCreates a cancel controller-HttpAbortController-
isCancelTells whether an error is a cancel; pass the caught error directlyerror: HttpError | nullboolean-
uploadUploads a fileinput: UploadInputPromise<UploadResult>-
downloadDownloads a fileinput: DownloadInputPromise<DownloadResult>-

Instances are not callable

TS has no callable objects, so http(config) is invalid; write http.request(config) instead.

Instance config HttpConfig ​

create takes the same shape as the setDefaults patch; omitted fields keep the parent values.

FieldDescriptionTypeDefaultVersion
baseURLBase address; an empty string uses url as-isstring''-
headersDefault headers, lowercased-deduplicated after mergeJsonObject | null{}-
timeoutTimeout in msnumber60000-
validateStatusStatus check, 2xx passes by default(status: number) => boolean2xx-
metaDefault metadata, passed through to interceptors onlyHttpMetaInput{ toast: false, loading: false }-

Request config ​

request() takes HttpRequestConfig; the optional third argument of get / post is HttpCallConfig, where url / method / params / data are decided by the method itself and must not be passed.

FieldDescriptionTypeDefaultVersion
urlRequest address, required in HttpRequestConfigstring--
methodMethod name; invalid values warn and fall back to GETstring | nullGET-
headersHeaders for this request, overriding instance defaultsJsonObject | null--
paramsQuery values, only in HttpRequestConfigJsonObject | null--
dataRequest body, only in HttpRequestConfigJsonObject | string | null--
timeoutTimeout for this requestnumber60000-
validateStatusStatus check for this request(status: number) => boolean2xx-
metaMetadata for this request, field by field over the defaultsHttpMetaInput--
signalCancel signalHttpAbortSignal | nullnull-

Interceptors ​

MemberDescriptionSignatureVersion
interceptors.request.useRequest interceptor; returning null aborts the request(fn: (config: ResolvedHttpConfig) => ResolvedHttpConfig | null) => void-
interceptors.response.useResponse interceptor with an optional error handler(onFulfilled: (response: HttpResponse) => any, onRejected?: (error: HttpError) => HttpError) => void-

Every onFulfilled receives the same HttpResponse; the last non-null return value becomes the resolved value. onRejected handlers run in registration order and the last return value wins.

Response HttpResponse ​

FieldDescriptionTypeVersion
dataResponse body, shaped by the serverany-
statusHTTP status codenumber-
headersResponse headersany-
cookiesResponse cookiesArray<string>-
configFinal config of this requestResolvedHttpConfig-

Error HttpError ​

FieldDescriptionTypeVersion
codeError class: ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTORstring-
messageHuman-readable descriptionstring-
statusHTTP status code; 0 means no responsenumber-
dataResponse body, present when a response existsany-
errCodePlatform error code, valid for network errorsnumber-
configFinal config of this requestResolvedHttpConfig-
responsePresent when an HTTP response existsHttpResponse | null-

Upload and download ​

ParameterDescriptionTypeDefaultVersion
urlRequest addressstring--
filePathRequired for upload; optional for download, where omitting it returns a temp pathstring | null--
nameUpload form field namestring | nullfile-
formDataExtra upload form fieldsJsonObject | null--
headersHeaders for this requestJsonObject | null--
timeoutTimeout for this requestnumber60000-
metaMetadata for this requestHttpMetaInput--
signalCancel signalHttpAbortSignal | nullnull-
onProgressProgress callback; progress is 0-100(p: TransferProgress) => void--

TransferProgress fields: progress (0-100), transferred (bytes sent), total (total bytes). Upload resolves with UploadResult { data: string, status: number }; download resolves with DownloadResult { tempFilePath: string, status: number }.

Notes ​

  • create inherits defaults only; interceptors must be registered again on the derived instance.
  • data is ignored with a warning on GET / HEAD; use params for query values.
  • validateStatus accepts a function only. To pass every status, use (): boolean => true; null is not supported.
  • upload strips content-type after merging so the platform can build the multipart header with its own boundary.
  • Upload and download also run through request interceptors and validateStatus, and reject with HttpError on failure.
  • Always test cancels with http.isCancel(e); never write e is HttpError, which compiles to an undefined identifier on H5.
  • Reusing an aborted signal rejects immediately with ERR_CANCELED; create a new controller for a new request.