/** * 网络请求封装 */ import { getAccessToken } from "./storage"; // 请求配置类型 export type RequestConfig = { url: string; method?: "GET" | "POST" | "PUT" | "DELETE"; data?: UTSJSONObject | null; header?: UTSJSONObject | null; timeout?: number; }; // 基础 URL // const BASE_URL = "http://192.168.110.105:8080"; // const BASE_URL = "http://222.243.138.146:5095" //测试服务器; const BASE_URL = "http://222.243.138.146:5097" //正式服务器; // const BASE_URL = "http://10.170.129.135:8089"; // const BASE_URL = "http://222.243.138.146:5096/prod-api" // const BASE_URL = "http://10.170.129.135/prod-api"; /** * 获取基础 URL */ export const getBaseUrl = (): string => { return BASE_URL; }; /** * 网络请求封装 */ export const request = (config: RequestConfig): Promise => { return new Promise((resolve, reject) => { // 获取 AccessToken const accessToken = getAccessToken(); // 设置请求头(先设置默认值,再合并自定义 header) const header: UTSJSONObject = { "Content-Type": "application/json", }; // 添加 AccessToken if (accessToken != null) { header["Authorization"] = 'Bearer ' + accessToken; } // 合并自定义 header(会覆盖默认值) if (config.header != null) { const customHeader = config.header as UTSJSONObject; // 遍历自定义 header 的所有键值对 for (const key in customHeader) { header[key] = customHeader[key]; } if(config.header['isToken'] == false){ header["Authorization"] = "" } } // 发起请求 uni.request({ url: BASE_URL + config.url, method: config.method ?? "GET", data: config.data, header: header, timeout: config.timeout ?? 30000, success: (res) => { // 提取属性(any 类型不能直接访问属性) console.log(config.url, "==", res); const statusCode = res.statusCode as number; const resData = res.data; if (statusCode == 200) { // 将响应数据转换为 UTSJSONObject,然后手动提取属性 const result = resData as UTSJSONObject; let code = result["code"] as number | null; let msg = result["msg"] as string | null; if (code == 200) { // 返回整个 result 对象 resolve(result as any); }else if (code != null && (code == 401)) { // 有些接口使用 code 字段 handleLoginRedirect(); console.log(config.url, "==", result); reject(new Error("登录已过期,请重新登录")); }else if (code != null && (code == 403)) { // 有些接口使用 code 字段 const errorMsg = msg != null ? msg : "请求失败"; reject(new Error(errorMsg)); } else { const errorMsg = msg != null ? msg : "请求失败"; reject(new Error(errorMsg)); } } else { reject(new Error(`请求失败:${statusCode}`)); } }, fail: (err: any) => { console.error("请求失败"+BASE_URL + config.url, err); reject(new Error("网络请求失败")); }, }); }); }; /** * 跳转登录页 */ const handleLoginRedirect = (): void => { uni.showToast({ title: "登录已过期", icon: "none", }); setTimeout(() => { uni.reLaunch({ url: "/pages/login/index", }); }, 1500); };