HTTP 请求

HTTP 工具在 libs/console-core/src/utils/http.ts

自动携带的 Header

每个请求自动附加:

Authorization: Bearer {localStorage.token}
x-tenant-id: {localStorage.tenant_id}
Content-Type: application/json

基本用法

import { http } from '@readystart/console-core'

// GET
const res = await http.get<User>('/v1/users/info')

// POST
const res = await http.post<Todo>('/v1/todos/create', { title: 'Hello' })

// PUT
const res = await http.put<Todo>('/v1/todos/update', { id: '...', title: 'Updated' })

// DELETE
const res = await http.delete('/v1/todos/delete')

响应格式

所有接口返回统一格式:

interface ApiResponse<T> {
  statusCode: number  // 200 = 成功
  message: string
  data: T
}

错误处理

statusCode !== 200 时自动弹出 toast 错误提示。

使用 silent 选项禁用自动提示:

const res = await http.post('/v1/some-api', body, { silent: true })
if (res.statusCode !== 200) {
  // 自己处理错误
}

设置 Base URL

import { setBaseUrl } from '@readystart/console-core'

setBaseUrl('https://api.example.com')

完整示例

import { useState, useEffect } from 'react'
import { http } from '@readystart/console-core'

interface Todo {
  id: string
  title: string
  completed: boolean
}

export default function TodosPage() {
  const [todos, setTodos] = useState<Todo[]>([])

  useEffect(() => {
    http.post<Todo[]>('/v1/todos/list').then(res => {
      if (res.statusCode === 200) setTodos(res.data)
    })
  }, [])

  return (
    <ul>
      {todos.map(t => <li key={t.id}>{t.title}</li>)}
    </ul>
  )
}