/** * 网络请求封装 - 模拟所APP */ // API 基础地址(生产环境服务器地址) const BASE_URL: string = 'http://8.155.172.147:5010' // 请求超时时间 const TIMEOUT: number = 30000 // 响应数据类型 type ResponseData = { code: string msg: string data: any } // 请求配置类型 type RequestOptions = { url: string method?: string data?: UTSJSONObject | null header?: UTSJSONObject | null timeout?: number loading?: boolean loadingText?: string } /** * 请求拦截器 */ func requestInterceptor (config: RequestOptions): RequestOptions { const token = uni.getStorageSync('token') as string if (token !== null && token !== '') { config.header = { ...config.header, 'Authorization': `Bearer ${token}` } as UTSJSONObject } config.header = { 'Content-Type': 'application/json', ...config.header } as UTSJSONObject return config } /** * 响应拦截器 */ func responseInterceptor (response: UniRequestSuccessCallbackResult): Promise { const statusCode: number = response.statusCode const data = response.data as ResponseData if (statusCode === 200) { if (data.code === '0000') { return Promise.resolve(data) } else if (data.code === '0002') { uni.removeStorageSync('token') uni.reLaunch({ url: '/pages/login/login' }) return Promise.reject(new Error(data.msg || '请重新登录')) } else { uni.showToast({ title: data.msg || '请求失败', icon: 'none', duration: 2000 }) return Promise.reject(new Error(data.msg)) } } else if (statusCode === 401) { uni.removeStorageSync('token') uni.reLaunch({ url: '/pages/login/login' }) return Promise.reject(new Error('未授权')) } else { return Promise.reject(new Error(`网络错误: ${statusCode}`)) } } /** * 通用请求方法 */ func request (options: RequestOptions): Promise { let config: RequestOptions = { url: options.url.startsWith('http') ? options.url : BASE_URL + options.url, method: options.method || 'GET', data: options.data || null, header: options.header || null, timeout: options.timeout || TIMEOUT } config = requestInterceptor(config) const showLoading = options.loading !== false if (showLoading) { uni.showLoading({ title: options.loadingText || '加载中...', mask: true }) } return new Promise((resolve, reject) => { uni.request({ url: config.url, method: config.method as UniRequestMethod, data: config.data, header: config.header, timeout: config.timeout, success: (response: UniRequestSuccessCallbackResult) => { responseInterceptor(response).then(resolve).catch(reject) }, fail: (error: UniRequestFailCallbackResult) => { uni.showToast({ title: error.errMsg || '网络请求失败', icon: 'none', duration: 2000 }) reject(new Error(error.errMsg)) }, complete: () => { if (showLoading) uni.hideLoading() } }) }) } /** * GET 请求 */ export func get (url: string, params: UTSJSONObject | null = null): Promise { return request({ url, method: 'GET', data: params }) } /** * POST 请求 */ export func post (url: string, data: UTSJSONObject | null = null): Promise { return request({ url, method: 'POST', data: data }) } export const config = { BASE_URL, TIMEOUT }