xtraderClient/docs/api/request.md
2026-02-25 14:46:10 +08:00

1.5 KiB
Raw Blame History

request.ts

路径src/api/request.ts

功能用途

HTTP 请求基础封装,提供 getpost 方法,支持自定义请求头(如鉴权 x-tokenx-user-id)。所有 API 模块均通过此文件发起请求。

核心能力

  • 统一 BASE_URL默认 https://api.xtrader.vip,可通过环境变量 VITE_API_BASE_URL 覆盖
  • CLOB WebSocket URLgetClobWsUrl() 返回与 REST API 同源的 ws(s)://host/api/clob/ws
  • GET 请求:支持 query 参数,自动序列化
  • POST 请求:支持 JSON body
  • 自定义 headers通过 RequestConfig.headers 传入

使用方式

import { get, post, getClobWsUrl } from '@/api/request'

// CLOB WebSocket URL与 REST 同源)
const wsUrl = getClobWsUrl() // e.g. wss://api.xtrader.vip/api/clob/ws

// GET 请求
const data = await get<MyResponse>('/path', { page: 1, keyword: 'x' })

// 带鉴权
const data = await get<MyResponse>('/path', undefined, {
  headers: { 'x-token': token, 'x-user-id': userId },
})

// POST 请求
const res = await post<MyResponse>('/path', { key: 'value' }, {
  headers: { 'x-token': token },
})

扩展方式

  1. 添加 PUT/DELETE:仿照 get/post 实现 putdel 函数
  2. 统一错误处理:在 get/post 内对 !res.ok 做统一 toast 或错误上报
  3. 请求/响应拦截:在 fetch 前后加入拦截逻辑(如 loading、日志
  4. 超时控制:使用 AbortController 实现超时取消