http — Request
17:43Description
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.
| Capability | What you get |
|---|---|
| Instance derivation | http.create(config) derives an independent instance with deep-merged defaults — one per host or service |
| Request methods | request as the general entry, plus get / delete / head / post / put / patch |
| Interceptors | Request 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 overrides | baseURL / headers / timeout / validateStatus / meta set per instance, overridable per call |
| Timeout | Instance default plus per-call override, 60000ms by default |
| Status validation | validateStatus(status) for custom rules, 2xx by default |
| Cancellation | abortController() with signal; isCancel(e) tells cancellation from real failures |
| Upload / download | upload / download with 0-100 progress callbacks, sharing defaults, interceptors and the error model |
| Page state | useRequest exposes loading / data / error with stale-response dropping, cancel-on-rerun and cancel-on-unmount |
| Metadata | meta (e.g. toast / loading) is visible to interceptors only, for global toasts, skeletons and tracking |
| Error model | HttpError.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
usecalls stack up in registration order; returningnullfrom 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 withHttpError, so error handling is shared. - Cancellation is first-class —
abortControllerworks together withuseRequest, which cancels on unmount;isCancelcovers the common "cancel is not an error" check.
Compatibility
| Platform | Support | Notes |
|---|---|---|
| App | ✅ Supported | Built on uni.request / uni.uploadFile / uni.downloadFile |
| H5 | ✅ Supported | Downloads resolve to a blob temp path; cross-origin calls need CORS |
| WeChat Mini Program | ✅ Supported | Add 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
<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
<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
<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
<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
<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
<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
<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.
| Method | Description | Parameters | Returns | Version |
|---|---|---|---|---|
| create | Derives a new instance: inherits defaults (deep merged), not interceptors | config?: HttpConfig | HttpInstance | - |
| request | Generic entry, url is required | config: HttpRequestConfig | Promise<any> | - |
| get / delete / head | Read requests, query values go through params | url: string, params?: JsonObject, config?: HttpCallConfig | Promise<any> | - |
| post / put / patch | Write requests, body goes through data | url: string, data?: JsonObject | string, config?: HttpCallConfig | Promise<any> | - |
| setDefaults | Merges a patch into the instance defaults | patch: HttpConfig | void | - |
| abortController | Creates a cancel controller | - | HttpAbortController | - |
| isCancel | Tells whether an error is a cancel; pass the caught error directly | error: HttpError | null | boolean | - |
| upload | Uploads a file | input: UploadInput | Promise<UploadResult> | - |
| download | Downloads a file | input: DownloadInput | Promise<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.
| Field | Description | Type | Default | Version |
|---|---|---|---|---|
| baseURL | Base address; an empty string uses url as-is | string | '' | - |
| headers | Default headers, lowercased-deduplicated after merge | JsonObject | null | {} | - |
| timeout | Timeout in ms | number | 60000 | - |
| validateStatus | Status check, 2xx passes by default | (status: number) => boolean | 2xx | - |
| meta | Default metadata, passed through to interceptors only | HttpMetaInput | { 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.
| Field | Description | Type | Default | Version |
|---|---|---|---|---|
| url | Request address, required in HttpRequestConfig | string | - | - |
| method | Method name; invalid values warn and fall back to GET | string | null | GET | - |
| headers | Headers for this request, overriding instance defaults | JsonObject | null | - | - |
| params | Query values, only in HttpRequestConfig | JsonObject | null | - | - |
| data | Request body, only in HttpRequestConfig | JsonObject | string | null | - | - |
| timeout | Timeout for this request | number | 60000 | - |
| validateStatus | Status check for this request | (status: number) => boolean | 2xx | - |
| meta | Metadata for this request, field by field over the defaults | HttpMetaInput | - | - |
| signal | Cancel signal | HttpAbortSignal | null | null | - |
Interceptors
| Member | Description | Signature | Version |
|---|---|---|---|
| interceptors.request.use | Request interceptor; returning null aborts the request | (fn: (config: ResolvedHttpConfig) => ResolvedHttpConfig | null) => void | - |
| interceptors.response.use | Response 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
| Field | Description | Type | Version |
|---|---|---|---|
| data | Response body, shaped by the server | any | - |
| status | HTTP status code | number | - |
| headers | Response headers | any | - |
| cookies | Response cookies | Array<string> | - |
| config | Final config of this request | ResolvedHttpConfig | - |
Error HttpError
| Field | Description | Type | Version |
|---|---|---|---|
| code | Error class: ERR_BAD_RESPONSE / ERR_NETWORK / ERR_CANCELED / ERR_INTERCEPTOR | string | - |
| message | Human-readable description | string | - |
| status | HTTP status code; 0 means no response | number | - |
| data | Response body, present when a response exists | any | - |
| errCode | Platform error code, valid for network errors | number | - |
| config | Final config of this request | ResolvedHttpConfig | - |
| response | Present when an HTTP response exists | HttpResponse | null | - |
Upload and download
| Parameter | Description | Type | Default | Version |
|---|---|---|---|---|
| url | Request address | string | - | - |
| filePath | Required for upload; optional for download, where omitting it returns a temp path | string | null | - | - |
| name | Upload form field name | string | null | file | - |
| formData | Extra upload form fields | JsonObject | null | - | - |
| headers | Headers for this request | JsonObject | null | - | - |
| timeout | Timeout for this request | number | 60000 | - |
| meta | Metadata for this request | HttpMetaInput | - | - |
| signal | Cancel signal | HttpAbortSignal | null | null | - |
| onProgress | Progress 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
createinheritsdefaultsonly; interceptors must be registered again on the derived instance.datais ignored with a warning onGET/HEAD; useparamsfor query values.validateStatusaccepts a function only. To pass every status, use(): boolean => true;nullis not supported.uploadstripscontent-typeafter merging so the platform can build themultipartheader with its ownboundary.- Upload and download also run through request interceptors and
validateStatus, and reject withHttpErroron failure. - Always test cancels with
http.isCancel(e); never writee is HttpError, which compiles to an undefined identifier on H5. - Reusing an aborted
signalrejects immediately withERR_CANCELED; create a new controller for a new request.