| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import Taro from '@tarojs/taro'
- import ResponsePolyfill from './response-polyfill'
- import { hc } from './hono-client/client'
- // API配置
- const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:8080'
- // 完整的API地址
- // const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
- // 创建自定义fetch函数,适配Taro.request
- const taroFetch: any = async (input, init) => {
- const url = typeof input === 'string' ? input : input.url
- const method = init.method || 'GET'
-
- const requestHeaders: Record<string, string> = init.headers;
- const keyOfContentType = Object.keys(requestHeaders).find(item => item.toLowerCase() === 'content-type')
- if (!keyOfContentType) {
- requestHeaders['content-type'] = 'application/json'
- }
- // 构建Taro请求选项
- const options: Taro.request.Option = {
- url,
- method: method as any,
- data: init.body,
- header: requestHeaders
- }
- // 添加token
- const token = Taro.getStorageSync('mini_token')
- if (token) {
- options.header = {
- ...options.header,
- 'Authorization': `Bearer ${token}`
- }
- }
- try {
- // const response = await Taro.request(options)
- console.log('options', options)
- const response = await Taro.request(options)
- console.log('response', response)
- const responseHeaders = response.header;
- // if (response.header) {
- // for (const [key, value] of Object.entries(response.header)) {
- // responseHeaders.set(key, value);
- // }
- // }
- // 处理204 No Content响应,不设置body
- const contentType = responseHeaders['content-type'] || responseHeaders['Content-Type'];
- const body = response.statusCode === 204
- ? null
- : (contentType && contentType.includes('application/json'))
- ? JSON.stringify(response.data)
- : response.data;
- return new ResponsePolyfill(
- 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 extends any>() => {
- // @ts-ignore
- return hc<T>(`${API_BASE_URL}`, {
- fetch: taroFetch
- })
- }
|