56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
import Taro from '@tarojs/taro'
|
|
|
|
// const BASE_URL = 'http://175.24.73.253:8001' // 改为实际后端IP
|
|
const BASE_URL = 'http://127.0.0.1:8001'
|
|
|
|
class ApiError extends Error {
|
|
constructor(public status: number, message: string) {
|
|
super(message)
|
|
}
|
|
}
|
|
|
|
async function request<T>(
|
|
url: string,
|
|
options: {
|
|
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
|
data?: any
|
|
headers?: Record<string, string>
|
|
} = {}
|
|
): Promise<T> {
|
|
const token = Taro.getStorageSync('token')
|
|
console.log(`[API] ${options.method || 'GET'} ${url}`, token ? 'with token' : 'no token')
|
|
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
...options.headers,
|
|
}
|
|
if (token) {
|
|
headers['Authorization'] = `Bearer ${token}`
|
|
}
|
|
|
|
const response = await Taro.request({
|
|
url: `${BASE_URL}${url}`,
|
|
method: options.method || 'GET',
|
|
data: options.data,
|
|
header: headers,
|
|
})
|
|
|
|
console.log(`[API] Response status:`, response.statusCode)
|
|
|
|
if (response.statusCode >= 400) {
|
|
const detail = response.data?.detail || 'Request failed'
|
|
throw new ApiError(response.statusCode, detail)
|
|
}
|
|
|
|
return response.data
|
|
}
|
|
|
|
export { request, ApiError, BASE_URL }
|
|
|
|
export function getToken(): string {
|
|
return Taro.getStorageSync('token') || ''
|
|
}
|
|
|
|
export function getCurrentUserId(): number {
|
|
return Taro.getStorageSync('user_id') || 0
|
|
} |