| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- import Taro from '@tarojs/taro'
- // API配置
- const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
- const API_VERSION = process.env.TARO_APP_API_VERSION || 'v1'
- // 完整的API地址
- const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
- // 请求拦截器
- const requestInterceptor = (options: Taro.request.Option) => {
- // 添加token
- const token = Taro.getStorageSync('token')
- if (token) {
- options.header = {
- ...options.header,
- 'Authorization': `Bearer ${token}`
- }
- }
-
- // 设置基础URL
- options.url = `${BASE_URL}${options.url}`
-
- // 设置默认header
- options.header = {
- 'Content-Type': 'application/json',
- ...options.header
- }
-
- return options
- }
- // 响应拦截器
- const responseInterceptor = (response: Taro.request.SuccessCallbackResult<any>) => {
- const { statusCode, data } = response
-
- if (statusCode === 200 || statusCode === 201) {
- // 检查数据结构,支持后端返回的格式
- if (data && data.data) {
- return data.data
- }
- return data
- } else if (statusCode === 401) {
- // 未授权,清除token并跳转到登录页
- Taro.removeStorageSync('token')
- Taro.removeStorageSync('userInfo')
- Taro.navigateTo({ url: '/pages/login/index' })
- throw new Error('请重新登录')
- } else {
- throw new Error(data.message || '请求失败')
- }
- }
- // 错误处理
- const errorHandler = (error: any) => {
- console.error('API Error:', error)
- Taro.showToast({
- title: error.message || '网络错误',
- icon: 'none'
- })
- throw error
- }
- // 封装请求方法
- class ApiClient {
- async request(options: Taro.request.Option) {
- try {
- const finalOptions = requestInterceptor(options)
- const response = await Taro.request(finalOptions)
- return responseInterceptor(response)
- } catch (error) {
- errorHandler(error)
- }
- }
- async get(url: string, params?: any) {
- return this.request({
- url,
- method: 'GET',
- data: params
- })
- }
- async post(url: string, data?: any) {
- return this.request({
- url,
- method: 'POST',
- data
- })
- }
- async put(url: string, data?: any) {
- return this.request({
- url,
- method: 'PUT',
- data
- })
- }
- async delete(url: string) {
- return this.request({
- url,
- method: 'DELETE'
- })
- }
- }
- // 创建单例实例
- export const apiClient = new ApiClient()
- // 认证相关API
- export const authApi = {
- // 密码登录
- login: (data: { username: string; password: string }) =>
- apiClient.post('/auth/login', data),
-
- // 用户注册
- register: (data: { username: string; password: string; email?: string }) =>
- apiClient.post('/auth/register', data),
-
- // 获取当前用户信息
- getCurrentUser: () =>
- apiClient.get('/auth/me'),
-
- // 退出登录
- logout: () =>
- apiClient.post('/auth/logout')
- }
- // 用户相关API
- export const userApi = {
- // 获取用户列表
- getUsers: (params?: any) =>
- apiClient.get('/users', params),
-
- // 获取单个用户信息
- getUser: (id: number) =>
- apiClient.get(`/users/${id}`),
-
- // 更新用户信息
- updateUser: (id: number, data: any) =>
- apiClient.put(`/users/${id}`, data),
-
- // 删除用户
- deleteUser: (id: number) =>
- apiClient.delete(`/users/${id}`)
- }
- export default apiClient
|