http.uts
3.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* 新系统 HTTP 请求客户端
* - Base: baseUrl(env.uts 按环境选取)
* - 公共路径前缀: /api
* - 鉴权: Bearer Token(自动从 storage.sessionId 注入)
* - 数据格式: JSON
* - 401 自动跳转登录页
*/
import { baseUrl } from "./env.uts";
import { storage } from "@/utils/storage.uts";
/** 401 时清理会话并跳转登录页 */
function redirectLogin(reject: (e: any) => void): void {
storage.set("sessionId", "", 0);
storage.set("userInfo", {} as UTSJSONObject, 0);
uni.hideLoading();
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
if (currentPage.route != "pages/common/login/index") {
uni.reLaunch({ url: "/pages/common/login/index" });
}
}
reject("登录已过期,请重新登录");
}
/**
* 新系统统一请求函数
* @param path 接口路径,自动拼接 `${baseUrl}/api` + path,如 `/auth/login`
* @param data 请求体(POST)或查询参数(GET)
* @param method HTTP 方法,默认 POST
* @returns 响应 data 字段(code===0 时)
*/
export function request(
path: string,
data: UTSJSONObject = {} as UTSJSONObject,
method: "GET" | "POST" = "POST"
): Promise<any> {
console.log("🚀 ~ request ~ data:", data)
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (netRes) => {
if (netRes.networkType == "none") {
uni.hideLoading();
uni.showToast({ title: "网络异常", icon: "none" });
reject("网络异常");
return;
}
// Bearer Token 鉴权
const token = storage.get("sessionId");
const header: UTSJSONObject = { "Content-Type": "application/json" };
if (token != null && `${token}` !== "") {
header.Authorization = `Bearer ${token}`;
}
const fullUrl = `${baseUrl}/api${path}`;
console.log("🚀 ~ request ~ fullUrl:", fullUrl)
uni.request({
url: fullUrl,
data,
method,
header,
dataType: "json",
timeout: 30_000,
success: (response) => {
console.log("🚀 ~ request ~ response:", response)
const statusCode = response.statusCode;
const resData = response.data;
// HTTP 层错误
if (resData == null || statusCode < 200 || statusCode >= 300) {
uni.hideLoading();
// 401 → 登录过期
if (statusCode == 401) {
redirectLogin(reject);
return;
}
const errMsg = resData == null
? "获取数据失败,请重试"
: `服务器错误(${statusCode})`;
console.log("🚀 ~ request ~ errMsg:", errMsg)
uni.showToast({ title: errMsg, icon: "none" });
reject(errMsg);
return;
}
// 业务层解析
const obj = resData as UTSJSONObject;
const code = obj["code"];
// 兼容数字 0 和字符串 "0"
if (code !== 0 && `${code}` !== "0") {
const msg = obj["message"] != null ? `${obj["message"]}` : "请求失败";
uni.showToast({ title: msg, icon: "none" });
reject(msg);
return;
}
// code === 0,返回 data 字段
const payload = obj["data"];
resolve(payload != null ? (payload as any) : ({} as UTSJSONObject));
},
fail: (error) => {
console.log("🚀 ~ request ~ error:", error)
uni.hideLoading();
const msg = error != null && error.errMsg != null
? `${error.errMsg}`
: "网络请求失败";
uni.showToast({ title: msg, icon: "none" });
reject(msg);
}
});
},
fail: () => {
reject("获取网络状态失败");
}
});
});
}