1.5 KiB
1.5 KiB
request.ts
路径:src/api/request.ts
功能用途
HTTP 请求基础封装,提供 get 和 post 方法,支持自定义请求头(如鉴权 x-token、x-user-id)。所有 API 模块均通过此文件发起请求。
核心能力
- 统一 BASE_URL:默认
https://api.xtrader.vip,可通过环境变量VITE_API_BASE_URL覆盖 - CLOB WebSocket URL:
getClobWsUrl()返回与 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 },
})
扩展方式
- 添加 PUT/DELETE:仿照
get/post实现put、del函数 - 统一错误处理:在
get/post内对!res.ok做统一 toast 或错误上报 - 请求/响应拦截:在 fetch 前后加入拦截逻辑(如 loading、日志)
- 超时控制:使用
AbortController实现超时取消