跪拜 Guibai
← Back to the summary

uni-app x Gets an Axios-Style Request Library with Cancellation, Unified Errors, and a useRequest Hook

【Full platform support】 uni-app x dedicated request library: axios style, multi-instance, interceptors, cancellable, upload/download

Previously, the http encapsulation library in uView Pro component library couldn't be used directly in uni-app x projects.

So I rewrote one based on axios's skeleton, and put it directly in the uView Pro X component library, exported also as http. So when you use the uView Pro X component library, you don't need to install an extra package; you can just use it. It also supports derivation via create, multi-domain baseURL configuration, interceptors, timeout, status code judgment, cancellation, upload/download progress, and useRequest tri-state, all in one. On failure, it uniformly rejects an HttpError.

Let's see how to use it.

First, basic usage

First create a global instance, put it in a file, mainly declare some base info, shared across the project:

// api/request.uts
import { http } from '@/uni_modules/uview-pro-x';
import type { HttpInstance } from '@/uni_modules/uview-pro-x';

const headers = new UTSJSONObject();
headers['content-type'] = 'application/json';

export const request: HttpInstance = http.create({
    baseURL: 'https://api.example.com',
    timeout: 15000,
    headers
});

This is enough to send requests.

If a page needs to load user info, a full example looks like this:

<template>
    <view class="page">
        <text v-if="loading">Loading…</text>
        <text v-else-if="error != null">{{ errorText }}</text>
        <text v-else>{{ userName }}</text>
        <ux-button text="Refresh" type="primary" @click="run()" />
    </view>
</template>

<script setup lang="uts">
import { useRequest } from '@/uni_modules/uview-pro-x';
import type { HttpCallConfig } from '@/uni_modules/uview-pro-x';
import { request } from '@/api/request';

type User = { id: string; name: string };

const { loading, data, error, run } = useRequest<User>(async (ctx) => {
    const res = await request.get('/user/1', null, { signal: ctx.signal } as HttpCallConfig);
    return res as User;
}, { immediate: true });

const userName = computed((): string => {
    const user = data.value;
    return user == null ? '' : user.name;
});

const errorText = computed((): string => {
    const err = error.value;
    return err == null ? '' : err.message;
});
</script>

In the template, directly write loading and error without .value; Vue will unwrap them. To write corresponding copy, put it in computed to avoid non-null assertions in the template. UTS doesn't support !.

Isn't that concise? There are many more usages, like multi-domain config, request/response interceptors, request cancellation, etc.

Design choices

Instances are derived

http itself is usable; http.create(config) derives a new one from it. When deriving, it deep-merges parent defaults, so you only write the items that differ from the parent.

For multi-backend projects, split instances by backend: one for business, one for files, each with its own baseURL and timeout. No need to check the domain before a request, and no need to branch by URL prefix in interceptors.

Note: derived instances only inherit defaults, not interceptors. This is not an oversight; axios does the same: interceptors often depend on the instance's own context, e.g., a service needs a dedicated signature.

The practical approach is to extract setupInterceptors(instance) as a function and call it once per instance, so nothing is missed.

// api/interceptors.uts
import type { HttpError, HttpResponse, HttpInstance, ResolvedHttpConfig } from '@/uni_modules/uview-pro-x';

export function setupInterceptors(instance: HttpInstance): void {
    instance.interceptors.request.use((config: ResolvedHttpConfig): ResolvedHttpConfig | null => {
        const token = uni.getStorageSync('token') as string;
        if (token != '') {
            config.headers['authorization'] = 'Bearer ' + token;
        }
        return config;
    });

    instance.interceptors.response.use((response: HttpResponse): any => {
        return response.data;
    }, (error: HttpError): HttpError => {
        return error;
    });
}

The return response.data in the response interceptor is the only place in the whole library that unwraps the response; the page gets business data directly, no need for res.data.data every time.

Interceptors use arrays, not a single slot

The single-slot approach has a concentrated problem: later added ones override earlier registered ones, no one reports an error, and the earlier one silently stops working, which can be time-consuming to debug.

Here, use appends to an array and executes in registration order. If any callback in the request chain returns null, the request is aborted and rejected with ERR_CANCELED.

The response chain has a different convention: each callback receives the same HttpResponse object, and the last non-null return value is the final result.

Not doing chained value passing is intentional: UTS type assertions can easily crash in chained passing, especially after encrypted compilation. To see the raw response structure, any callback can access status and headers.

request.interceptors.response.use((response: HttpResponse): any => {
    if (response.status == 204) {
        return null;
    }
    return response.data;
});

Cancellation needs its own fallback

uni.request returns a RequestTask, no Promise, no signal. The current approach: each request creates a controller; on abort(), first reject with ERR_CANCELED yourself, then call task.abort().

uni does not guarantee the fail callback after abort; if you only call task.abort(), the Promise will hang forever, and loading will spin indefinitely. Adding "settle first, then abort" ensures the worst case doesn't miss anything.

const controller = http.abortController();

request.get('/slow', null, { signal: controller.signal } as HttpCallConfig)
    .catch((e: any) => {
        if (http.isCancel(e)) return;  // cancellation is not an error, don't show a toast
        // real failure
    });

controller.abort();

The parameter type of isCancel is HttpError | null; internally it only reads code, without type checking. The reason will be mentioned later.

Only four error codes

On failure, always reject an HttpError. Currently the library only declares four code values:

For page-level judgment, use code. It's recommended not to match message, because the copy may change and message changes with it, but code won't.

catch (e: any) {
    const err = e as HttpError;
    if (err.code == 'ERR_NETWORK') {
        // prompt to check network, give a retry button
    } else if (err.code == 'ERR_BAD_RESPONSE') {
        // err.status is the real status code like 404 / 500
    } else if (err.code == 'ERR_CANCELED') {
        // silent
    }
}

useRequest does only four things

This Hook doesn't send requests; sending still goes through the instance, so interceptors and defaults still take effect. What pages must handle and often miss:

  1. Tri-state: loading / data / error
  2. Race condition discarding: number each run, and if the returning result doesn't match the latest number, discard it
  3. Unmount cancellation: abort in onUnmounted
  4. Cancel previous before re-running: when run() is called again, first cancel the last one

Search boxes that request while typing, list filters that switch quickly, all encounter the problem of "old requests returning later than new ones." At that point, judging by loading is insufficient; you need a sequence number.

const { loading, data, error, run, cancel } = useRequest<Order[]>(async (ctx) => {
    const list = await request.get('/orders', params, { signal: ctx.signal } as HttpCallConfig);
    return list as Order[];
});

// Filter changed, re-run, old one is automatically invalidated
const onFilterChange = (): void => {
    run();
};

immediate defaults to false; if you want to send a request as soon as the page loads, you must explicitly pass { immediate: true }, or call run() in onMounted. The default not running is to let the page decide when to send the request, not the Hook secretly deciding.

Integration requires three steps

  1. Create an instance. For multi-domain, build multiple instances per domain.
  2. Attach interceptors. Extract setupInterceptors as a function and call it once at the end of the instance file.
  3. Use useRequest in the page. Write tri-state in the template, put copy in computed, don't write data.value.name directly in the template.

If you don't want to use the Hook, you can also directly await request.get(...); then you manage the tri-state yourself. It's not mandatory.

Upload and download

upload and download are methods on the instance, using the same defaults, the same request interceptor, the same validateStatus, and on failure still reject HttpError, so you only need to write error messages once.

const result = await http.upload({
    url: '/upload',
    filePath: tempPath,
    name: 'file',
    onProgress: (p) => {
        progress.value = p.progress;  // 0-100
    }
});

Some details: upload automatically strips content-type, letting the platform generate a multipart header with boundary; setting it manually will break it. The data returned by upload is a string; if you need JSON, JSON.parse it yourself. Download without filePath lands in the platform's temp directory and returns tempFilePath.

Pitfalls I stepped in

Things it doesn't do

Finally

Sending a request in a project is about three lines: await request.get(...), wrapped in useRequest, and write tri-state in the template. App, H5, and mini-programs run the same code without conditional compilation.

Where the token comes from, how 404 is prompted, whether requests stop when leaving the page, whether old responses override new ones. These are now handled by the library; developers just focus on business.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

Mapleeeeeee

Can you explain what vapor mode actually is? What are its usage scenarios?

前端梦工厂

It's a rendering mode, similar to Vue's virtual DOM mode.