/** * 兼容旧版API的请求工具 * 这个文件是为了保持向后兼容性,让现有的API代码能够正常工作 * 逐步迁移完成后可以删除此文件 */ import { getRaw, postRaw, putRaw, delRaw } from './request'; import { BaseUrl, TenantId } from "@/config/app"; import Taro from '@tarojs/taro'; let baseUrl = BaseUrl; // 开发环境 if (process.env.NODE_ENV === 'development') { // baseUrl = 'http://localhost:9200/api' } // 兼容旧版的request函数 export function request(options: any): Promise { const token = Taro.getStorageSync('access_token'); const header: Record = { 'Content-Type': 'application/json', 'TenantId': Taro.getStorageSync('TenantId') || TenantId }; if (token) { header['Authorization'] = token; } // 构建完整URL let url = options.url; if (url.indexOf('http') === -1) { url = baseUrl + url; } // 根据方法调用对应的新请求函数 const method = (options.method || 'GET').toUpperCase(); const config = { header: { ...header, ...options.header }, showError: false // 让API层自己处理错误 }; switch (method) { case 'GET': return getRaw(url, null, config); case 'POST': return postRaw(url, options.data, config); case 'PUT': return putRaw(url, options.data, config); case 'DELETE': return delRaw(url, options.data, config); default: return getRaw(url, null, config); } } // 兼容旧版的便捷方法 export function get(url: string, data?: any): Promise { if (url.indexOf('http') === -1) { url = baseUrl + url; } if (data) { // 处理查询参数 if (data.params) { // 如果data有params属性,使用params作为查询参数 const queryString = Object.keys(data.params) .filter(key => data.params[key] !== undefined && data.params[key] !== null) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data.params[key])}`) .join('&'); if (queryString) { url += `?${queryString}`; } } else { // 否则直接使用data作为查询参数 const queryString = Object.keys(data) .filter(key => data[key] !== undefined && data[key] !== null) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`) .join('&'); if (queryString) { url += `?${queryString}`; } } } return getRaw(url, null, { showError: false }); } export function post(url: string, data?: any): Promise { if (url.indexOf('http') === -1) { url = baseUrl + url; } return postRaw(url, data, { showError: false }); } export function put(url: string, data?: any): Promise { if (url.indexOf('http') === -1) { url = baseUrl + url; } return putRaw(url, data, { showError: false }); } export function del(url: string, data?: any): Promise { if (url.indexOf('http') === -1) { url = baseUrl + url; } return delRaw(url, data, { showError: false }); } export default { request, get, post, put, del };