Skip to content
Development guideVersion 6.0.2

Requests, cancellation, and mocks ​

Business code calls functions in apps/admin/src/api, which use request from @/axios. On success, the instance resolves with the response body T. On failure, it rejects. The business layer unwraps any additional API envelope. Use an Axios instance that returns the full response when you need raw headers or status codes.

Interactive example ​

View example source
tsx
import type { ApiResponse } from '@/api/admin/contracts'
import {
  getRequestFixture,
  getWeather,
  requestFixtureUrl,
} from '@/api/demo/test'
import { useHookPlusRequest, useRequest } from '@/axios'
import { useI18n } from '@/hooks'
import { NButton, NCard, NFormItem, NInput, NSelect, NTag } from 'naive-ui'
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'

export default defineComponent({
  name: 'RAxios',
  setup() {
    const { t } = useI18n('demoDetails')
    const manual = useRequest<
      ApiResponse<Awaited<ReturnType<typeof getRequestFixture>>>
    >(
      { url: requestFixtureUrl, method: 'get', cancelConfig: { cancel: true } },
      { manual: true },
    )
    const city = ref<string | null>(null)
    const weather = useHookPlusRequest(getWeather, { manual: true })
    const cities = ['Hangzhou', 'Shanghai', 'Chengdu'].map((value) => ({
      value,
      label: value,
    }))
    const rateDemos = (['throttle', 'debounce'] as const).map((kind) => {
      const input = ref('')
      const sent = ref(0)
      const inputId = useId()
      const query = useHookPlusRequest(
        async (value: string) => {
          sent.value += 1
          const { ticket } = await getRequestFixture()

          return { value, ticket: ticket.id }
        },
        {
          manual: true,
          ...(kind === 'throttle'
            ? { throttleWait: 1000 }
            : { debounceWait: 1000 }),
        },
      )

      return { kind, input, sent, inputId, query }
    })

    return () => (
      <DemoPage
        title={t('request.title')}
        description={t('request.intro')}
        meta={t('request.fixture')}
      >
        <div class="r-demo-grid">
          <NCard title="useRequest">
            <div class="r-demo-card-stack">
              <NButton type="primary" onClick={() => manual.run()}>
                {t('request.fetch')}
              </NButton>
              <DemoResult label={t('result')} error={!!manual.error.value}>
                {manual.loading.value ? (
                  t('loading')
                ) : manual.error.value ? (
                  t('request.failed')
                ) : manual.data.value ? (
                  <pre>
                    {JSON.stringify(manual.data.value.data.ticket, null, 2)}
                  </pre>
                ) : (
                  t('request.waiting')
                )}
              </DemoResult>
            </div>
          </NCard>
          <NCard title={t('request.city')}>
            <div class="r-demo-card-stack">
              <NSelect
                value={city.value}
                options={cities}
                placeholder={t('request.selectCity')}
                onUpdateValue={(value) => {
                  city.value = value
                  weather.run(value)
                }}
              />
              <DemoResult label={t('result')} error={!!weather.error.value}>
                {weather.loading.value
                  ? t('loading')
                  : weather.error.value
                    ? t('request.failed')
                    : weather.data.value
                      ? `${weather.data.value.temperature} °C · ${weather.data.value.humidity}% RH`
                      : t('request.waiting')}
              </DemoResult>
            </div>
          </NCard>
          {rateDemos.map(({ kind, input, sent, inputId, query }) => (
            <NCard key={kind} title={t(`request.${kind}`)}>
              {{
                'header-extra': () => (
                  <NTag size="small" bordered={false}>
                    {t('request.sent', { count: sent.value })}
                  </NTag>
                ),
                default: () => (
                  <div class="r-demo-card-stack">
                    <NFormItem
                      label={t('request.input')}
                      labelProps={{ for: inputId }}
                      showFeedback={false}
                    >
                      <NInput
                        value={input.value}
                        inputProps={{ id: inputId }}
                        onUpdateValue={(value) => {
                          input.value = value

                          if (value.trim()) query.run(value)
                          else query.cancel()
                        }}
                      />
                    </NFormItem>
                    <DemoResult
                      label={t('request.last')}
                      error={!!query.error.value}
                    >
                      {query.loading.value ? (
                        t('loading')
                      ) : query.error.value ? (
                        t('request.failed')
                      ) : query.data.value ? (
                        <code>
                          {query.data.value.value} · {query.data.value.ticket}
                        </code>
                      ) : (
                        t('request.waiting')
                      )}
                    </DemoResult>
                  </div>
                ),
              }}
            </NCard>
          ))}
        </div>
      </DemoPage>
    )
  },
})

Send and cancel requests ​

ts
import { request } from '@/axios'

interface Order {
  id: string
  customer: string
}

export function loadOrders(
  params: Record<string, unknown>,
  signal: AbortSignal,
) {
  return request<{ data: Order[]; total: number }>({
    method: 'get',
    url: '/api/orders',
    params,
    signal,
    cancelConfig: { cancel: false },
  })
}

The default canceler identifies duplicate requests by URL, method, query, and body. It compares the encoded parameter sequence for URLSearchParams and the ordered fields, text values, and file instances for FormData. The default layout cancels managed requests before the route updates. Callers that supply signal or set cancelConfig.cancel: false manage cancellation themselves. In the example above, TablePro owns the signal.

Configuration and interceptors ​

  • Set baseURL, timeouts, and default headers in apps/admin/src/app-config/request-config.ts.
  • Register plugins in apps/admin/src/axios/axios-interceptor/{request,response}/provider.ts. Put request headers, auth responses, and other concerns in the corresponding plugins.
  • useRequest wraps the same client. Call it within an active Vue effect scope.

Switch from demo to a real service ​

Development, production preview, and GitHub Pages use the same MSW HTTP mocks. Sign-in, users, routes, people tables, route-demo details, business search options, charts, and request examples all go through the API layer. A service worker under the application base responds in the hosted demo. Table examples with local filtering first fetch data through the API and then sort, paginate, and filter locally. Request and response types and runtime schemas live in @ray-template/api-contracts. @ray-template/http supplies the transport client.

Set VITE_API_MOCK=false and VITE_API_BASE_URL to send requests to your own server. See the backend integration guide for request and response formats, error codes, sessions, permissions, and the downloadable OpenAPI definition. Mock changes persist in the current browser. Your backend owns shared data and production sessions.

Request instance · Business APIs

useRequest and manual execution ​

Import useRequest<Response>(fetchOptions, options?) from @/axios to run the given configuration through the template Axios instance. It forwards options to vue-hooks-plus, including manual and success or error callbacks. Data, errors, loading state, and the execution methods come from the upstream hook. Create it in setup or an active effect scope.

ts
import { useRequest } from '@/axios'

export function useOrderSummary() {
  return useRequest<{ total: number }>(
    { url: '/api/orders/summary', method: 'get' },
    { manual: true },
  )
}

Call run() to load manually. The wrapper reads its configuration from fetchOptions. For a dynamic service with parameters, import useHookPlusRequest(service, options?) from the same entry point and call request inside the service. Business code or response interceptors own error notifications. The default interceptors ignore the optional responseSuccessMessage and responseErrorMessage type fields.

The template injects Authorization: Bearer <token> only for the configured API base and preserves caller-provided auth headers. Configure a separate client explicitly for third-party URLs.

Request hook · Request configuration types · Header injection