新增小程序后端代码,包括数据库、路由、服务层等。
小程序前后端打通,包括登录、注册、绑定设备、查询绑定信息,修改小朋友名称等功能。
This commit is contained in:
56
banban-mini/src/services/api.ts
Normal file
56
banban-mini/src/services/api.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user