| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- import Taro from '@tarojs/taro'
- import { hc } from 'hono/client'
- // API配置
- const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
- // 完整的API地址
- // const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
- // 创建自定义fetch函数,适配Taro.request
- const taroFetch: typeof fetch = async (input, init) => {
- const url = typeof input === 'string' ? input : input.url
- const method = init.method || 'GET'
-
- const requestHeaders: Record<string, string> = {};
- if (init.headers instanceof Headers) {
- init.headers.forEach((value, key) => {
- requestHeaders[key] = value;
- })
- }
- // 构建Taro请求选项
- const options: Taro.request.Option = {
- url,
- method: method as any,
- data: init.body,
- header: requestHeaders
- }
- // 添加token
- const token = Taro.getStorageSync('token')
- if (token) {
- options.header = {
- ...options.header,
- 'Authorization': `Bearer ${token}`
- }
- }
- try {
- const response = await Taro.request(options)
- const responseHeaders = new Headers();
- if (response.header) {
- for (const [key, value] of Object.entries(response.header)) {
- responseHeaders.set(key, value);
- }
- }
- // 处理204 No Content响应,不设置body
- const body = response.statusCode === 204
- ? null
- : responseHeaders.get('content-type')!.includes('application/json')
- ? JSON.stringify(response.data)
- : response.data;
- return new Response(
- body,
- {
- status: response.statusCode,
- statusText: response.errMsg || 'OK',
- headers: responseHeaders
- }
- )
- } catch (error) {
- console.error('API Error:', error)
- Taro.showToast({
- title: error.message || '网络错误',
- icon: 'none'
- })
- throw error
- }
- }
- // 创建Hono RPC客户端
- export const rpcClient = <T>() => {
- return hc<T>(`${API_BASE_URL}`, {
- fetch: taroFetch
- })
- }
|