Skip to content

Request Best Practices ​

17:43

Description ​

Do not call http.create in every page. Keep the instance, its defaults and its interceptors in one module file, and let pages import that instance. An ESM module runs once per runtime, so the instance is naturally an application-level singleton: every page shares the same baseURL, timeout, headers, token injection and unwrapping rules.

Relationship with http

http is the library's built-in default instance (empty baseURL, no business interceptors); the request derived in api/request.ts is the business instance. Pages should only import request and never modify http.

Suggested layout ​

api/
├── request.ts       business instance: defaults + export
├── interceptors.ts  reusable interceptors, installable on any instance
└── user.ts          API functions (optional; pages never build URLs)
pages/
└── user/index.uvue   page: import request or API functions

Create the business instance ​

ts
// api/request.ts
import { http } from '@/uni_modules/uview-pro-x';
import { setupInterceptors } from './interceptors';

// Default headers: created once per module
const defaultHeaders = new JsonObject();
defaultHeaders['content-type'] = 'application/json';
defaultHeaders['x-client'] = 'uview-pro-x';

// Business instance: inherit http defaults, then override baseURL / timeout / headers
const request = http.create({
    baseURL: 'https://api.example.com',
    timeout: 15000,
    headers: defaultHeaders
});

// Interceptors are not inherited by create, register them explicitly
setupInterceptors(request);

export { request };

Register interceptors ​

Write interceptors as an "install onto any instance" function so the main instance and multi-domain instances share the same logic.

ts
// api/interceptors.ts
import type { HttpInstance } from '@/uni_modules/uview-pro-x';

export function setupInterceptors(instance: HttpInstance): void {
    instance.interceptors.request.use((config) => {
        // config.url already contains the full address, so credentials can be scoped by domain
        if (!config.url.startsWith('https://api.example.com')) {
            return config;
        }
        // Read storage on every request: a refreshed token takes effect immediately
        const raw = uni.getStorageSync('token');
        let token = '';
        if (raw != null && typeof raw == 'string') {
            token = raw as string;
        }
        if (token.length > 0) {
            config.headers['authorization'] = 'Bearer ' + token;
        }
        return config;
    });

    instance.interceptors.response.use((res) => {
        // Unwrap: pages receive business data instead of HttpResponse
        return res.data;
    }, (error) => {
        // Cancels are normal flow, do not notify
        if (error.code != 'ERR_CANCELED') {
            uni.showToast({ title: error.message, icon: 'none' });
        }
        // Must return: the return value becomes the final rejection
        return error;
    });
}

Registration timing

setupInterceptors runs at the top level of api/request.ts, which loads once, so interceptors are registered exactly once. Never call it again inside a page: there is no eject, the array only grows, so every page visit would add another layer.

Use it in a page ​

The page imports the same module instance, so defaults and interceptors apply automatically and the page only deals with data and state.

vue
<template>
    <ux-button text="Load user" type="primary" @click="load()" />
    <text>{{ summary }}</text>
</template>

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

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

const summary = ref<string>('Not loaded');

const load = (): void => {
    // The response interceptor already unwrapped the body
    request.get('/user/1').then((data: any) => {
        const user = data as User;
        summary.value = user.name;
    }).catch((e: any) => {
        const err = e as HttpError;
        summary.value = err.code + ' · HTTP ' + err.status.toString();
    });
};
</script>

Wrapping API functions keeps URLs and types out of pages entirely:

ts
// api/user.ts
import { request } from './request';

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

export function fetchUser(id: number): Promise<any> {
    return request.get('/user/' + id.toString());
}
ts
// In a page
import { fetchUser } from '@/api/user';
import type { User } from '@/api/user';

const load = (): void => {
    fetchUser(1).then((data: any) => {
        const user = data as User;
        console.log(user.name);
    });
};

When you need loading / error states, wrap the same request call with useRequest; the instance and interceptors stay unchanged.

Multiple domains ​

Pick by scenario:

ScenarioApproachInherits defaultsInherits interceptors
Occasional third-party API or static assetPass an absolute URL- (baseURL is skipped)Yes
Long-lived second domain (uploads, open platform)request.create({ baseURL })YesNo, register again
Fully independent credentials / timeout / interceptorshttp.create({ baseURL })NoNo, register again

Option 1: absolute URL (occasional) ​

When url starts with http://, https:// or //, baseURL is not prepended, so the request goes straight to the external host:

ts
// Third-party status check, baseURL is not used
request.get('https://open.example.com/v1/status').then((data: any) => {
    console.log(data);
});

params is still serialized and appended, so absolute and relative URLs behave identically.

External requests still run through global interceptors

An absolute URL does not skip interceptors. If the interceptor injects authorization unconditionally, the token would be sent to a third-party domain. That is why setupInterceptors above checks config.url before injecting credentials.

Option 2: derive a second instance (long-lived domain) ​

When a domain is used long-term or needs its own timeout, derive a dedicated instance and install the interceptors it needs:

ts
// api/cdn.ts
import { request } from './request';
import { setupInterceptors } from './interceptors';

// Derive from the business instance: inherits headers and other defaults, overrides baseURL and timeout
const cdnRequest = request.create({
    baseURL: 'https://cdn.example.com',
    timeout: 30000
});

// create does not inherit interceptors, register them again
setupInterceptors(cdnRequest);

export { cdnRequest };

Thanks to the domain allowlist inside setupInterceptors, this instance skips token injection (its config.url is not the main domain), which is usually what you want. If the second domain needs different credentials, do not reuse that function; write and use a separate interceptor set.

You cannot override baseURL per request ​

The third argument of get / post is HttpCallConfig, which only has headers / timeout / validateStatus / meta / signal — there is no baseURL:

ts
// Invalid: HttpCallConfig has no baseURL, type checking fails immediately
request.get('/list', null, { baseURL: 'https://other.example.com' });

To change the host you either pass an absolute URL (single call) or create an instance (long-lived).

Things to avoid ​

PatternConsequence
request.interceptors.request.use(...) inside a pageAdds a layer per page visit, and there is no eject to remove it
request.setDefaults({...}) inside a pageMutates the application-level singleton; every page is affected
request.defaults.headers['x'] = ... inside a pageSame as above, and later request.create instances inherit the header
Using http.create({...}) as the business instanceLoses business headers and interceptors; one config per page, impossible to govern
http.setDefaults({...}) inside a pagePollutes the library default instance; every later http.create is affected

Notes ​

  • The instance is a singleton: top-level code in api/request.ts runs on first import, so all pages share it. request.create() always returns a new instance with no interceptors.
  • Read the token inside the interceptor: reading it once at module scope means login / logout never refreshes it.
  • config.url is already fully built: changing url in an interceptor takes effect directly; the library will not prepend baseURL again.
  • Unwrapping only affects request and the method helpers: upload() resolves UploadResult and download() resolves DownloadResult, untouched by the response interceptor.
  • Returning null from a request interceptor aborts the request: it rejects with ERR_CANCELED, which is handy for "do not send when signed out"; test it with http.isCancel(e).
  • Pages still need catch: interceptors only notify and log; the rejection still propagates, and an uncaught one produces an unhandled-rejection warning. Use useRequest when you want automatic states.
  • Avoid duplicate toasts in interceptors: concurrent failures fire showToast repeatedly; add de-duplication or throttling if needed.